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;
}
}
例如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 61. Rotate List
- LeetCode:Rotate List
- 个人记录-LeetCode 61. Rotate List
- [LeetCode] Rotate List
- [LeetCode] Rotate List
- 【LEETCODE】61- Rotate List [Python]
- leetcode61 Rotate List
- LeetCode(61) Rotate List
- LeetCode 61. Rotate List(循环右移单链表)
- Rotate List leetcode java
- leetcode Rotate List
- leetcode 刷题之路 13 Rotate List
- leetcode之Rotate List
- Leetcode:61. Rotate List
- Leetcode61 rotate list
- LeetCode 60 Rotate List
- LeetCode刷题笔录 Rotate List
- leetcode[61]Rotate List
- leetcode之Rotate List
- [leetcode] Rotate List