2021年3月4日 周四天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
本文目录
1. 题目简介
2. 题解(模拟法)
朴实无华的模拟法:思路类似于 Leetcode 92. 反转链表 II,只不过更复杂一些,需要每次根据头尾结点反转k
个结点,然后把断掉的地方接上,直到剩下的结点不足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(k==1) return head;
ListNode* hair = new ListNode(0);
hair->next = head;
ListNode* pre = hair;
while(head){
ListNode* cur = pre;
// 查看剩余部分长度是否大于等于 k
for(int i=0;i<k;++i){
cur = cur->next;
if(cur==nullptr)
return hair->next;
}
ListNode* tail = cur;
pair<ListNode*,ListNode*> p = reverseBetween(head,tail);
head = p.first;
tail = p.second;
// 把子链表重新接回原链表
pre->next = head;
pre = tail;
head = tail->next;
}
return hair->next;
}
// 翻转一个子链表,并且返回新的头与尾
pair<ListNode*,ListNode*> reverseBetween(ListNode* head, ListNode* tail){
ListNode* nex = head->next;
ListNode* cur = head;
while(cur!=tail){
head->next = nex->next;
nex->next = cur;
cur = nex;
nex = head->next;
}
return {
tail,head};
}
};
参考文献
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/k-ge-yi-zu-fan-zhuan-lian-biao-by-leetcode-solutio/