code1:使用快慢指针法,快指针先走k步,然后两个指针一起走,当快指针走到末尾时,慢指针的下一个位置是新的顺序的头结点,这样就可以旋转链表,
注意边界条件:原链表为空时,直接返回NULL,还有就是当k大于链表长度和k远远大于链表长度时该如何处理,我们需要首先遍历一遍原链表得到链表长度n,然后k对n取余,这样k肯定小于n
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null) return null;
int n=0;
ListNode cur=head;
while(cur!=null){
n++;
cur=cur.next;
}
k %=n;
ListNode fast=head,slow=head;
for(int i=0;i<k;i++)
if(fast !=null) fast=fast.next;
if(fast==null)
return head;
while(fast.next !=null){
fast=fast.next;
slow=slow.next;
}
fast.next=head;
fast=slow.next;
slow.next=null;
return fast;
}
}
code2:一个指针就够了,原理是先遍历整个链表获得链表长度n,然后此时把链表头和尾链接起来,在往后走n - k % n个节点就到达新链表的头结点前一个点,这时断开链表即可
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null )
return null;
int n=1;
ListNode cur=head;
while(cur.next !=null){
n++;
cur=cur.next;
}
cur.next=head;
int m=n-k%n;
for(int i=0;i<m;i++)
cur=cur.next;
ListNode newhead=cur.next;
cur.next=null;
return newhead;
}
}