1. Stack-Based Value / Node Extraction
Intuition
1. Traverse the linked list and push every node reference onto a stack.
2. Create a dummy head node.
3. Repeatedly pop from the stack and append each node to the end of the new chain.
4. Set the final node's next pointer to null.
5. Return dummy.next.
When to apply: Quick conceptual demonstration leveraging stack data structures.
Algorithm
- Push all nodes onto stack.
- Pop nodes sequentially and re-link.
- Set terminal pointer to null.
#include <iostream>#include <stack> 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* reverseList(ListNode* head) { if (!head || !head->next) return head; std::stack<ListNode*> st; ListNode* curr = head; while (curr != nullptr) { st.push(curr); curr = curr->next; } ListNode dummy(0); ListNode* tail = &dummy; while (!st.empty()) { tail->next = st.top(); st.pop(); tail = tail->next; } tail->next = nullptr; 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.reverseList(head); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— One pass to push N nodes and one pass to pop N nodes: O(N) total. - Space complexity:
O(N)— Stack holds references to all N nodes in memory: O(N) extra space.