题目:
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
.
题目分析:
1、边界情况:k = 1,不用处理;链表为空或者长度为1,不用处理
2、将右边k个节点移动到链表前端,最起码需要知道链表长度
3、可能出现k>len的情况
4、正常的链表运算将两段拼接
思路:
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 (k == 0) return head;
if (head == nullptr || head->next == nullptr) return head;
int len = 1;
ListNode* pre = head;
ListNode* p = head;
while (p->next != nullptr) {
len++;
p = p->next;
}
int offset = k % len;
if (offset == 0) return head;
for (int i = 1; i < (len - offset); i++) pre = pre->next;
ListNode* newHead = pre->next;
ListNode* end = newHead;
pre->next = nullptr;
while (end->next != nullptr) end = end->next;
end->next = head;
return newHead;
}
};