leetcode61. 旋转链表
程序员文章站
2022-05-06 09:39:33
...
/**
* 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 == nullptr || head->next == nullptr)
{
return head;
}
vector<int> v;
while(head)
{
v.push_back(head->val);
head = head->next;
}
vector<int> temp = v;
for(int i = 0; i < temp.size(); i++)
{
v.push_back(temp[i]);
}
int len = k % temp.size();
vector<int> res;
for(int i = temp.size() - len; i < temp.size() - len + temp.size(); i++)
{
res.push_back(v[i]);
}
ListNode* r = new ListNode(0);
ListNode* dummynode = r;
for(int i = 0; i < res.size(); i++)
{
dummynode->val = res[i];
if(i == res.size() - 1)
{
break;
}
dummynode->next = new ListNode(0);
dummynode = dummynode->next;
}
return r;
}
};
上一篇: pdfmake的使用以及对中文的支持
下一篇: go 语言实现简单的学生管理系统