题目链接:25. K 个一组翻转链表 - 力扣(LeetCode)
解题思路:
代码比较难理解的点在于:
从实际中演示一遍就可以明白
代码:
递归代码:
/**
* 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) {
int cnt=k;
ListNode* last=head;
while(last){
cnt--;
last=last->next;
if(cnt==0) break;
}
if(cnt!=0) return head;
ListNode * cur =head->next;
head->next=reverseKGroup(last,k);
cnt=k;
while(--cnt){
ListNode* tmp=cur->next;
cur->next=head;
head=cur;
cur=tmp;
}
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:
pair<ListNode*,ListNode*> fz(ListNode* head,ListNode* tail){
ListNode * prev=tail->next;
ListNode* p=head;
while(prev!=tail){
ListNode* nex=p->next;
p->next=prev;
prev=p;
p=nex;
}
return {tail,head};
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* hair=new ListNode(-1,head);
ListNode* pre=hair;
while(head){
ListNode* tail=pre;
for(int i=0;i<k;i++){
tail=tail->next;
if(!tail) return hair->next;
}
ListNode* nex=tail->next;
tie(head,tail)=fz(head,tail);
pre->next=head;
tail->next=nex;
pre=tail;
head=tail->next;
}
return hair->next;
}
};