题目链接
https://leetcode-cn.com/problems/rotate-list/
题目
给你一个链表的头节点
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 *
思路一
先用数组储存所有元素,再重新赋值。
C++ Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//用数组存放 取的时候从每个位置+k取 +k后大于n取余
if(!head) return head;
vector<int> L;
ListNode* cur=head;
while(cur)
{
L.push_back(cur->val);
cur=cur->next;
}
int n=L.size();
int i=0;
cur=head;
if(k>n) k=k%n;
while(cur)
{
if(i-k>=0) cur->val=L[i-k];
else cur->val=L[n+(i-k)];
i++;
cur=cur->next;
}
return head;
}
};
思路二
首位相连,形成环,再找新的头结点断开。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//先找到尾,再找切开的节点
if(!head)return head;
ListNode* tail=head;
ListNode* pre;
int length=1;
while(tail->next){
//找到结尾和节点个数
length++;
tail=tail->next;
}
int step=k%length;
if(step==0)return head;
tail->next=head;
while(length-step){
length--;
pre=head;
head=head->next;
}
pre->next=nullptr;
return head;
}
};