题目
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
解
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode p1 = head;
int count = 1;
while (p1.next != null) {
count++;
p1 = p1.next;
}
p1.next = head;
k = k% count;
ListNode p2 = head;
for (int i = 0; i < count - k - 1; i++) {
p2 = p2.next;
}
ListNode result = p2.next;
p2.next = null;
return result;
}
}