您的位置:首页 > 其它

Rotate List

2015-07-14 08:31 211 查看
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
if (k < 0) {
return head;
}
int length = 0;
ListNode ptr = head;
while (ptr != null) {
ptr = ptr.next;
length++;
}
int shift = k % length;
if (shift == 0) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
for (int i = 0; i < shift; i++) {
fast = fast.next;
}
ListNode slow = dummy;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
fast.next = dummy.next;
dummy.next = slow.next;
slow.next = null;
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息