Print Immutable Linked List in Reverse - Problem

You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:

ImmutableListNode: An interface of immutable linked list, you are given the head of the list.

You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):

  • ImmutableListNode.printValue(): Print value of the current node.
  • ImmutableListNode.getNext(): Return the next node.

The input is only given to initialize the linked list internally. You must solve this problem without modifying the linked list. In other words, you must operate the linked list using only the mentioned APIs.

Input & Output

Example 1 — Basic List
$ Input: head = [1,2,3,4]
Output: 4 3 2 1
💡 Note: Print each value in reverse order: start with 4 (last node), then 3, 2, and finally 1 (first node)
Example 2 — Single Node
$ Input: head = [1]
Output: 1
💡 Note: Only one node, so print its value: 1
Example 3 — Two Nodes
$ Input: head = [1,2]
Output: 2 1
💡 Note: Print in reverse: 2 (second node) then 1 (first node)

Constraints

  • 1 ≤ Number of nodes ≤ 1000
  • 0 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Print Immutable Linked List in Reverse INPUT Immutable Linked List 1 2 3 4 head Available APIs: node.printValue() node.getNext() Constraint: Cannot modify the list No direct node access head = [1, 2, 3, 4] ALGORITHM STEPS 1 Base Case If node is null, return 2 Recurse First Call reverse(node.getNext()) 3 Print After node.printValue() 4 Stack Unwinds Prints in reverse order Call Stack Visualization: reverse(1) --> print 1 reverse(2) --> print 2 reverse(3) --> print 3 reverse(4) --> print 4 unwind FINAL RESULT Printed Output (in order): 4 First 3 2 1 Last OK - Reversed Output! Output: 4, 3, 2, 1 Key Insight: Recursion naturally reverses the order! By calling getNext() BEFORE printValue(), we traverse to the end first. As the call stack unwinds, each node prints in reverse order. Time: O(n), Space: O(n) for stack. TutorialsPoint - Print Immutable Linked List in Reverse | Recursive Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
843 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen