题目
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
- 链表中节点的数目在范围
[0, 500]
内 -100 <= Node.val <= 100
0 <= k <= 2 * 109
解决方案一
- 判断链表长度,此时一个ListNode的指针怕p1指向最后一个结点
- 创建新的指针p2,从链表头到倒数第k+1个结点
- 将p2到p1的链表放在表头
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head || !head->next) return head;
ListNode *new_head = new ListNode(0, head);
ListNode *fast=new_head, *temp=new_head;
int i = 0, n = 0;
while(temp->next){n++; temp = temp->next;}
k = k % n;
while(--n >= k){fast = fast->next;}
temp->next = new_head->next;
new_head->next = fast->next;
fast->next = nullptr;
return new_head->next;
}
};
效果:
- 231/231 cases passed (8 ms)
- Your runtime beats 78.98 % of cpp submissions
- Your memory usage beats 46.39 % of cpp submissions (11.4 MB)