61. Rotate List
Description
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
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
Analysis
方法一就是简单粗暴地每次将最后一个元素插入到第一个元素,重点是要设一个fakeHead指针指向头结点之前的节点。
方法二是讲链表闭合成一个环,这样的话每次插入不用改变链表的顺序,只截取其中新的head和tail即可。
还有一个tips就是在计算插入次数k的时候,要取模k=k%(链表长度)。否则会time limit exceeded。
Code
方法一:设一个fakeHead指向head的前一个值(fakeHead->next = head)。每次插入的时候将链表最后一个值插到fakeHead->next,然后将倒数第二个值的next设为NULL。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head==NULL || head->next==NULL || k==0) return head;
ListNode* fakeHead = new ListNode(0);
fakeHead->next = head;
ListNode* p = head;
int length = 0;
while(p){
p = p->next;
length++;
}
cout<<length<<endl;
k = k%length;
p = head;
while(k>0){
ListNode* pre = p;
while(p->next){
pre = p;
p = p->next;
}
p->next = fakeHead->next;
fakeHead->next = p;
pre->next = NULL;
k--;
}
return fakeHead->next;
}
};
方法二(SOLUTION: JAVA):
将链表闭合成一个环,让链表最后一个值tail->next = head。然后计算new_tail和new_head各是第几个元素,然后将new_tail前面那个元素的next设为NULL。最后返回new_head。
class Solution {
public ListNode rotateRight(ListNode head, int k) {
// base cases
if (head == null) return null;
if (head.next == null) return head;
// close the linked list into the ring
ListNode old_tail = head;
int n;
for(n = 1; old_tail.next != null; n++)
old_tail = old_tail.next;
old_tail.next = head;
// find new tail : (n - k % n - 1)th node
// and new head : (n - k % n)th node
ListNode new_tail = head;
for (int i = 0; i < n - k % n - 1; i++)
new_tail = new_tail.next;
ListNode new_head = new_tail.next;
// break the ring
new_tail.next = null;
return new_head;
}
}