题目描述
方法一)模拟
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){
ListNode* hair = new ListNode(0);
hair->next = head;
ListNode* pre = hair;
while(head){
ListNode* tail = pre;
for(int i=0;i<k;i++){
tail = tail->next;
if(!tail){
return hair->next; //不够k个说明到链表末尾了
}
}
ListNode* nex = tail->next;
// 翻转长度为k的子链表 这里是 C++17 的写法,也可以写成!!!
// pair<ListNode*, ListNode*> result = myReverse(head, tail);
// head = result.first;
// tail = result.second;
tie(head, tail) = myReverse(head, tail);
pre->next = head; //前后分别连接到原串
tail->next = nex;
pre = tail; //修改新的子串pre和子串头
head = tail->next;
}
return hair->next;
}
};