Leetcode:25. K 个一组翻转链表(C++带详细注释)
/**
* 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*> myReverse(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) {
int len=0;//链表长度
ListNode*tep=head,*pre;//临时变量和头插法头节点
ListNode*l=head;//最终返回链表
while(tep)//求链表长度
{
len++;
tep=tep->next;
}
if(len<k||k==1) return head;//长度小于k返回
int count=0;//计数循环几次
while(len>=k)//有完整的子链
{
tep=head;//让tep指向子链最后一个元素
for(int i=0;i<k-1;i++)
{
tep=tep->next;
}
tie(head, tep) = myReverse(head, tep);//反转子链
if(count==0) {l=head;pre=head;}//第一次循环记下头指针
else{//非第一次循环
for(int i=0;i<k-1;i++)//找到前面子链的最后一个元素
{
pre=pre->next;
}
pre->next=head;//链接上刚反转好的子链
pre=pre->next;//pre指向子链表头
}
head=tep->next;//移向下一个子链
len-=k;//求剩余长度
count++;//循环次数加一
}
return l;//返回结果
}
};