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
题意:每旋转一次,就是把最后一个结点放到最前面。
解法一:将首位相连,尾指针向后跑len - k % len 次,重新标记首尾结点。
/**
* 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) return head;
int len = 1;
ListNode *p = head;
while(p->next){
len++;
p = p->next;
}
k = len - k % len;
p->next = head;//首尾相连
for(int step = 0; step < k; ++step){
p = p->next;//往后跑
}
head = p->next;//新的首结点
p->next = NULL;//断开环
return head;
}
};
解法二:利用链表翻转,例如:
[1,2,3,4,5],2
- [3,2,1,4,5] 翻转前len - k个
- [3,2,1,5,4] 翻转后k个
- [4,5,1,2,3] 整体翻转
/**
* 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) return head;
int len = 1;
ListNode *tmp = head;
while(tmp && tmp->next){
tmp = tmp->next;
len++;
}
if(len < 2 || k % len == 0) return head;//排除长度小于2的和不需操作的
k %= len;
head = reverseBetween(head, 1, len - k);
head = reverseBetween(head, len - k + 1, len);
head = reverseBetween(head, 1, len);
return head;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {//链表翻转
if(head == NULL) return NULL;
ListNode dummy(-1);
dummy.next = head;
ListNode *pre = &dummy;
for(int i = 0; i < m-1; ++i)
pre = pre->next;
ListNode *head2 = pre;
pre = pre->next;
ListNode *cur = pre->next;
for(int i = m; i < n; ++i){
pre->next = cur->next;
cur->next = head2->next;
head2->next = cur;
cur = pre->next;
}
return dummy.next;
}
};