25. 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: // 翻轉一個子鏈表,并且返回新的頭與尾 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) { // hair->next保存的是整個鏈表的頭結點 ListNode* hair = new ListNode(0); hair->next = head; ListNode* pre = hair; // 循環里,head被重復作為每一組鏈表的第一個結點,tail被重復作為每一組鏈表的最后一個節點 while (head) { // pre->next保存每一組鏈表的第一個節點 ListNode* tail = pre; // 查看剩余部分長度是否大于等于 k for (int i = 0; i < k; ++i) { tail = tail->next; if (!tail) { return hair->next; } } // nex保存每一組鏈表最后一個節點的后繼節點 ListNode* nex = tail->next; pair<ListNode*, ListNode*> result = myReverse(head, tail); head = result.first; tail = result.second; // 這里是 C++17 的寫法 // tie(head, tail) = myReverse(head, tail); // 把子鏈表重新接回原鏈表 pre->next = head; tail->next = nex; // pre保存本組的最后一個節點,因此在下一次循環中,pre->next即為下一組的第一個節點, // 進而起到鏈接上下兩個組的作用 pre = tail; // 當鏈表的節點個數是k的整數時,最后一次翻轉之后,tail->next為nullptr,從而跳出循環 head = tail->next; } return hair->next; } };

浙公網安備 33010602011771號