Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
Solution:
public ListNode
rotateRight(ListNode head,
int k) {
if (head ==
null || head.next ==
null || k ==
0) {
return head;
}
ListNode left = head;
ListNode right = head;
int len =
1;
while (right.next !=
null) {
right = right.next;
len++;
}
k = len -
1 - k % len;
while (k >
0) {
left = left.next;
k--;
}
right.next = head;
head = left.next;
left.next =
null;
return head;
}
转载请注明原文地址: https://ju.6miu.com/read-40635.html