题目:
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
.
最正统的解法就是two pointers:定义两个指针p和q,然后先让q前进k步,接着让p和q同步前进直到q到达末尾。此时p的下一个节点就是未来新的头节点,所以此时修改p和q的next即可。本题除了需要注意two pointers的运行边界情况之外,还需要特别注意几个特殊情况:1)链表本身为空;2)k值大于链表的长度;3)更新后的k值为0。本题的时间复杂度为O(n),空间复杂度为O(1)。
代码:
/**
* 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 || k == 0) { // speicial case
return head;
}
ListNode *p = head, *q = head;
int len = 1;
while (q->next != NULL) { // get the length of the list
len++;
q = q->next;
}
k = k % len; // in case k is equal or larger than the length of the list
if (k == 0) {
return head;
}
q = head;
for (int i = 0; i < k; ++i) { // set the second pointer
q = q->next;
}
while (q->next != NULL) {
p = p->next;
q = q->next;
}
ListNode* newHead = p->next;
p->next = NULL;
q->next = head;
return newHead;
}
};