【力扣 090】25. K 個一組翻轉連結串列
阿新 • • 發佈:2022-05-30
24. 兩兩交換連結串列中的節點
給你連結串列的頭節點 head ,每 k 個節點一組進行翻轉,請你返回修改後的連結串列。
k 是一個正整數,它的值小於或等於連結串列的長度。如果節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。
你不能只是單純的改變節點內部的值,而是需要實際進行節點交換。
示例 1:
輸入:head = [1,2,3,4,5], k = 2
輸出:[2,1,4,3,5]
示例 2:
輸入:head = [1,2,3,4,5], k = 3
輸出:[3,2,1,4,5]
提示:
連結串列中的節點數目為 n
1 <= k <= n <= 5000
0 <= Node.val <= 1000
進階:你可以設計一個只用 O(1) 額外記憶體空間的演算法解決此問題嗎?
來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/reverse-nodes-in-k-group
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
程式碼實現:
/** * 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) { ListNode* cur = head; int count = 0; // Find the (k + 1)th node while (cur && count != k) { cur = cur->next; count++; } // less than k nodes left, do not reverse if (count < k) { return head; } // recursively (handle k+1)th to the end cur = reverseKGroup(cur, k); // reverse the first k nodes (in current k group) while (count > 0) { ListNode* next = head->next; head->next = cur; cur = head; head = next; count--; } head = cur; return head; } };