本文最后更新于 123 天前。
class Solution {
public:
//翻转一段链表,prev一开始是这段链表的后一个listnode(不属于这段链表),然后从头依次将这段链表的listnode的指针指向prev,head是链表第一个,tail是最后一个
pair<ListNode*, ListNode*>reverseList(ListNode *head, ListNode *tail){
ListNode *prev = tail->next;
ListNode *cur = head;
while(prev != tail){
ListNode *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return {tail, head};
}
ListNode* reverseKGroup(ListNode* head, int k) {//hair是不变的,prev,head,tail都在改变
ListNode *hair = new ListNode;
hair->next = head;
ListNode *prev = hair, *tail = hair;
while(head){
for(int i = 0;i < k;i++){
tail = tail->next;
if(!tail){
return hair->next;
}
}
tie(head, tail) = reverseList(head, tail);// 这里是 C++17 的写法,也可以写成
// pair<ListNode*, ListNode*> result = myReverse(head, tail);
// head = result.first;
// tail = result.second;
prev->next = head;
head = tail->next;
prev = tail;
}
return hair->next;
}
};