您的位置:首页 > 其它

leetcode: Rotate List

2014-06-19 15:13 267 查看
这道题的话,就是用一个相差为n的两个指针

例如1-2-3-4-5,n=2,

就让p1先走n步走到3

p2指向1,然后大家一起走,p1走到尾部5

p2走到3,新链表的头就是p2.next,再把p2.next置为null。

边界考虑:

n=0时,p2.next=null,这个新链表头就是原来的头。

n>=5的时候,首先要把n对链表长度取模。也就是说,当p1先走走到了头,知道这个时候n是大于链表长度,并且可以算出链表长度。就让p1重新先走一次。

public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head==null)
<span style="white-space:pre"> </span>return null;

ListNode newhead;
ListNode tail;
newhead=head;
tail=head;
int len=n;
while(tail.next!=null && len>0)
{
tail=tail.next;
len--;
}
//is n> lengt of the list?
if(tail.next==null && len>0)
{
len=n%(n-len+1);
tail=head;
while(tail.next!=null && len>0)
{
tail=tail.next;
len--;
}
}

while(tail.next!=null)
{
tail=tail.next;
newhead=newhead.next;
}

tail.next=head;
if(newhead.next!=null)
head=newhead.next;
newhead.next=null;
//System.out.println(tail.val+" "+newhead.val+" "+head.val);
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode