1. Stack-Based k-Group Node Buffer
Intuition
1. Maintain an explicit stack st.
2. Traverse the list. Push nodes onto st.
3. When st.size() == k, pop nodes one by one and attach to the result list.
4. If traversal finishes and st contains < k nodes, retrieve the nodes in their original FIFO order (e.g. from the bottom of stack) and append them without reversal.
When to apply: Quick prototype leveraging LIFO stack properties.
Algorithm
- Traverse linked list with pointer
curr. - Push nodes into stack until k nodes are collected.
- Pop all nodes to reverse group and attach to tail.
- If leftover nodes < k, attach them without reversal.
#include <iostream>#include <stack>#include <vector> 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) { if (!head || k <= 1) return head; ListNode dummy(0); ListNode* tail = &dummy; ListNode* curr = head; while (curr != nullptr) { std::vector<ListNode*> buffer; ListNode* temp = curr; while (temp != nullptr && buffer.size() < k) { buffer.push_back(temp); temp = temp->next; } if (buffer.size() == k) { for (int i = k - 1; i >= 0; --i) { tail->next = buffer[i]; tail = tail->next; } tail->next = nullptr; curr = temp; } else { tail->next = curr; break; } } return dummy.next; }}; int main() { ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); Solution sol; ListNode* res = sol.reverseKGroup(head, 2); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Each node is pushed and popped from the stack once: O(N) overall. - Space complexity:
O(k)— The stack stores at most k nodes at any time: O(k) extra memory.