{x}
blog image

Print Immutable Linked List in Reverse

Solution Explanation: Printing an Immutable Linked List in Reverse

This problem requires printing the nodes of an immutable linked list in reverse order using only the provided API: printValue() and getNext(). We cannot directly access or modify the list's structure.

Approach: Recursion

The most efficient and elegant solution uses recursion. The recursive function works as follows:

  1. Base Case: If the current node (head) is null (end of the list), the recursion stops.

  2. Recursive Step: If the current node is not null:

    • Recursively call the function with the next node (head.getNext()). This traverses the list to the end.
    • After the recursive call returns (meaning the end of the list has been reached), print the value of the current node using head.printValue(). This is the key to reversing the order – we print the values on the way back up the call stack.

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the number of nodes in the linked list. We visit each node once during the traversal.

  • Space Complexity: O(n) in the worst case. This is due to the recursive call stack. The maximum depth of the recursion is equal to the number of nodes in the list. In some languages, tail-call optimization might reduce this to O(1) in practice, but it's not guaranteed.

Code Examples (with detailed comments)

The following code examples demonstrate the recursive approach in various programming languages. Note that the ImmutableListNode interface is assumed to be pre-defined and provided as part of the problem's constraints.

Python:

# """
# This is the ImmutableListNode's API interface.
# You should not implement it, or speculate about its implementation.
# """
# class ImmutableListNode:
#     def printValue(self) -> None: # print the value of this node.
#     def getNext(self) -> 'ImmutableListNode': # return the next node.
 
 
class Solution:
    def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None:
        # Base case: End of the list
        if head is None:  
            return
 
        # Recursive step:
        self.printLinkedListInReverse(head.getNext()) # Go to the end first
        head.printValue() # Print the current node's value on the way back up

Java:

/**
 * // This is the ImmutableListNode's API interface.
 * // You should not implement it, or speculate about its implementation.
 * interface ImmutableListNode {
 *     public void printValue(); // print the value of this node.
 *     public ImmutableListNode getNext(); // return the next node.
 * };
 */
 
class Solution {
    public void printLinkedListInReverse(ImmutableListNode head) {
        if (head == null) { // Base case
            return;
        }
        printLinkedListInReverse(head.getNext()); // Recursive call
        head.printValue(); // Print after the recursive call returns
    }
}

(Other languages like C++, Go, TypeScript, C# would follow a very similar structure, adapting the syntax and null checks accordingly.)

Constant Space Solution (Follow-up)

Achieving constant space complexity for this problem is challenging (and perhaps impossible without modifying the immutable list itself, which is forbidden). The recursive solution inherently uses stack space proportional to the list's length. A constant-space iterative approach would require a substantial change to how we interact with the immutable linked list, likely needing additional data structures not provided by the API. It is highly probable that a constant-space solution is not possible under the given constraints.