题目:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
和之前有一道题特别类似,双指针,先把fast移动k然后两个一起移动。
自己写的时候这块儿写错了。不用一个一个移动,直接整体移就行了。
dummy的下一个是slow.next. 然后slow.next=null。fast。next就是head
Code:
public ListNode rotateRight(ListNode head, int k) {
if(head==null||head.next==null||k==0)
return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
ListNode count = dummy;
int len = 0;
while(count.next!=null){
count = count.next;
len++;
}
k = k%len;
if(k==0) return head;
for(int i=0;i<k;i++){
fast = fast.next;
}
while(fast.next!=null){
fast= fast.next;
slow = slow.next;
}
dummy.next = slow.next;
fast.next = head;
slow.next = null;
return dummy.next;
}