Problem Description
Given an immutable linked list, print out all node values in reverse order. You are provided with only two APIs:
• ImmutableListNode.getNext() to retrieve the next node, and
• ImmutableListNode.printValue() to print the current node’s value.
You cannot modify the linked list, so you must use one of the allowed methods to achieve the reverse order printing.
Key Insights
- The linked list is immutable, preventing any in-place modifications.
- Recursion naturally leverages the call stack to achieve a reverse order of operations.
- An iterative approach using an explicit stack is also a valid solution.
- The challenge constraints lead to O(n) time complexity with O(n) extra space for both recursive and stack-driven solutions.
Space and Time Complexity
Time Complexity: O(n) for traversing the list once
Space Complexity: O(n) due to the usage of the call stack in the recursion or an explicit stack
(Note: Constant space solutions are not applicable due to the immutability constraint.)
Solution
We solve this problem by utilizing either a recursive approach or an iterative approach with an explicit stack. In the recursive method, we traverse the linked list until the end and then print the nodes during the backtracking phase. This effectively prints the list in reverse order. Alternatively, we can traverse the list iteratively, pushing each node onto a stack, and then pop them to print in reverse order. Both methods satisfy the problem's requirements using only the provided API.