LeetCode#25.K 个一组翻转链表
程序员文章站
2022-03-05 09:04:05
...
25. K 个一组翻转链表
/**
* 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* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next || k<=1) return head;
ListNode * cur=head;
vector<ListNode*> list;
while(cur){
list.push_back(cur);
cur=cur->next;
}
if(list.size()<k) return head;
ListNode *dhead=new ListNode(-1),*pre=dhead;
for(int i=0;i<list.size()/k*k;i+=k){
pre->next=list[i+k-1];
for(int j=k-1;j>=1;--j){
list[j+i]->next=list[j+i-1];
}
pre=list[i];
}
if(list.size()%k!=0){
pre->next=list[list.size()/k*k];
}else{
pre->next=nullptr;
}
return dhead->next;
}
};
上一篇: 数据类型转换