题目描述:
Given a list, rotate the list to the right by kplaces, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
这个意思有点表达不清,翻译过来就是从倒数第k个节点开始,反转过来
思路:注意到这里的测试样例里k是有可能会大于这个链表的长度的,所以我们应该
1.先遍历一边求出这个链表的长度
2.要求倒数第k个节点,那么拿的前一个节点就是n-k节点(这里我们先在求链表长度的之后把这个链表绕成一个环)
3.找到n-k节点,断开就可以了
注释部分那个方法也是可以用的,不过不简练;
public ListNode rotateRight(ListNode head, int n) {
if(head==null||head.next==null||n==0)
return head;
int len=1;
ListNode cur=head;
while(cur.next!=null){
len++;
cur=cur.next;
}
//倒数第k节点 那么这个几点的前一个节点就是顺数 len-k个节点
n=len-n%len;//flag1
//先把这个链成环
cur.next=head;
//此时cur指向的还是head的上一个节点,我们要移动到第n(flag1处理后)个节点 则需要移动 n次;
for(int i=0;i<n;i++){
cur=cur.next;
}
ListNode nHead=cur.next;
cur.next=null;
return nHead;
}
/*
public ListNode rotateRight(ListNode head, int n) {
if(head==null||head.next==null||n==0)
return head;
int len=0;
ListNode cur=head;
while(cur!=null){
len++;
cur=cur.next;
}
n%=len;
if(n==0)
return head;
ListNode pre=head;
ListNode last=head;
for(int i=0;i<n;i++){
if(pre!=null)
pre=pre.next;
}
while(pre.next!=null){
pre=pre.next;
last=last.next;
}
ListNode nHead=last.next;
last.next=null;
pre.next=head;
return nHead;
}*/