题目链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
题目如下:
/**
* 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==NULL||head->next==NULL) return head;
ListNode* dummyHead=new ListNode();
dummyHead->next=head;
auto pre=dummyHead;
auto p=head;//p为交换k的起始位置;q为交换k的最后一个位置
while(p){
ListNode* q=p;
for(int i=1;i<k&&q!=NULL;i++) q=q->next;
if(q==NULL){
pre->next=p;
return dummyHead->next;
}else {
ListNode* temp=q->next;
vector<ListNode*> nodes=reverse(p,q);//返回值,0为头,1为尾
pre->next=nodes[0];
pre=nodes[1];
p=temp;
}
}
return dummyHead->next;
}
private://将head到tail位置的链表元素进行反转
vector<ListNode*> reverse(ListNode* head,ListNode* tail){
ListNode* newHead=NULL;
ListNode* p=head;
while(p!=tail){
ListNode* temp=p->next;
p->next=newHead;
newHead=p;
p=temp;
}
tail->next=newHead;//将最后一个tail节点,加至链头
newHead=tail;
return {newHead,head};//反转之后的头和尾
}
};