您的位置:首页 > 其它

Rotate List

2014-07-07 08:28 393 查看
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null) {
return null;
}
ListNode slow = head, fast = head;
for(int i = 0; i < n; i++) {
fast = fast.next;
if(fast == null) {
fast = head;
}
}
while(fast.next != null) {
slow = slow.next;
fast = fast.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
}


Time: O(n)

Space: O(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Linked List