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个节点,来旋转链表。
1 基本思路。普遍使用的dummynode ,还有pre,cur 两个来表示前后节点。一开始先test往后k格;之后cur和test同时移动,当test为null时,cur即为新的头节点。此时要做些操作,pre.next要为null,新的head为cur。之后到链表最后,接上原来的头节点即可,dummynode发挥用处。代码如下:
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(n<=0 || head == null|| head.next==null) {
return head;
}
ListNode dummynode = new ListNode(Integer.MIN_VALUE);
dummynode.next = head;
ListNode test =head;
while(n>0){
if(test==null){
test=head;
}
test=test.next;
n--;
}
ListNode pre = dummynode;
ListNode cur = head;
while(test!=null){
pre=cur;
cur=cur.next;
test=test.next;
}
head=cur;
pre.next=null;
while(cur!=null){
pre=cur;
cur=cur.next;
}
pre.next=dummynode.next;
return head;
}
}
细节