描述
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
设
代码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) return head;
ListNode *tmp = head;
int n = 1;
while (tmp->next) {tmp = tmp->next; n++;}
tmp->next = head;
n = n - k % n;
while(n--) tmp=tmp->next;
ListNode *res = tmp->next;
tmp->next = NULL;
return res;
}
};
分析2
另外一个方法是使用双指针,一个指针先走 k <script type="math/tex" id="MathJax-Element-326">k</script> 步,之后两个指针同时走,当快指针走到链表尾时,慢指针刚好走到新的表头处。
代码2
/**
* 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) return head;
ListNode *p1 = head, *p2 = head;
int n = 1;
while (p1->next) {p1 = p1->next; n++;}
k = k % n;
p1 = head;
while (k--) {p1 = p1->next;}
while (p1->next) {p1 = p1->next; p2 = p2->next;}
p1->next = head;
p1 = p2->next;
p2->next = NULL;
return p1;
}
};