您的位置:首页 > 其它

LeetCode Rotate List

2015-01-12 21:23 351 查看
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
.

使用两个指针,第一个先走k步,然后第二个开始走,知道第一个走到最后一个。

这样第二个指针正好是 len-k个,它就是新链表的最后一个元素。

/**
* 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) {
ListNode temp = head;
if(temp==null) return temp;
int len=0;
while (temp != null) {
++len;
temp = temp.next;
}
n = n % len;
ListNode fast=head;
ListNode slow = head;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast=fast.next;
slow = slow.next;
}
fast.next=head;
head = slow.next;
slow.next = null;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: