leetcode 25. K 个一组翻转链表
程序员文章站
2022-07-08 14:54:32
...
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head == nullptr)
{
return nullptr;
}
vector<int> vec;
vector<int> v;
vector<int> temp;
while(head)
{
vec.push_back(head->val);
head = head->next;
}
int len = vec.size();
int length = len / k * k;
for(int i = 0; i < length;)
{
temp.assign(&vec[i], &vec[i + k]);
reverse(temp.begin(), temp.end());
for(int i = 0; i < temp.size(); i++)
{
v.push_back(temp[i]);
}
temp.clear();
i += k;
}
for(int i = length; i < len; i++)
{
v.push_back(vec[i]);
}
ListNode* res = new ListNode(0);
ListNode* dummynode = res;
for(int i = 0; i < v.size(); i++)
{
dummynode->val = v[i];
if(i == v.size() - 1)
{
break;
}
dummynode->next = new ListNode(0);
dummynode = dummynode->next;
}
return res;
}
};