Skip to main content

25. Reverse Nodes in k-Group

  • Recursion
/**
* 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)
{
// cnt 計算需要反轉的 node 的數量
int cnt = 0;
ListNode* cur = head;
// 當需要反轉的 node 的數量小於 k 的時候
// 指標前進
while (cur && cnt < k)
{
cur = cur->next;
cnt++;
}

// 當需要反轉的 node 數量達到 k 時
if (cnt == k)
{
// 呼叫 reverseLinkedList,反轉 linked list
ListNode* reversedHead = reverseLinkedList(head, k);

// 遞迴反轉剩餘的 node
head->next = reverseKGroup(cur, k);
return reversedHead;
}
return head;
}

ListNode* reverseLinkedList(ListNode* head, int k)
{
ListNode* dummy = new ListNode();
ListNode* cur = head;
for (int i = 0; i < k; ++i)
{
ListNode* next_node = cur->next;
cur->next = dummy;
dummy = cur;
cur = next_node;
}
return dummy;
}
};
  • T: O(n)O(n)

  • S: O(n/k)O(n / k)

  • Iteration

  • T: O(n)O(n)
  • S: O(1)O(1)