Print Immutable Linked List in Reverse - Problem
Imagine you have a special linked list that you can only read but never modify. Your challenge is to print all the values in reverse order without breaking any rules!
You're given an ImmutableListNode representing the head of this immutable linked list. You have access to only two methods:
ImmutableListNode.printValue(): Print the current node's valueImmutableListNode.getNext(): Get the next node (or null if end)
The Challenge: Print all values in reverse order using only these two methods. You cannot modify the list, store the values directly, or access nodes through any other means.
For example, if the linked list contains [1, 2, 4, 3], you should print: 3, 4, 2, 1
Input & Output
example_1.py โ Basic Case
$
Input:
head = [1,2,4,3]
โบ
Output:
3
4
2
1
๐ก Note:
We traverse to the end recursively, then print values as we return: 3 (last) โ 4 โ 2 โ 1 (first)
example_2.py โ Single Node
$
Input:
head = [5]
โบ
Output:
5
๐ก Note:
Single node list - recursion reaches base case immediately, then prints the only value
example_3.py โ Two Nodes
$
Input:
head = [10,20]
โบ
Output:
20
10
๐ก Note:
Two recursive calls: first reaches 20, hits null, returns and prints 20, then prints 10
Constraints
-
The length of the linked list is in the range
[1, 1000] -
The value of each node in the linked list is in the range
[-1000, 1000] - Follow up: Could you solve it both recursively and iteratively?
-
You can only use the provided
ImmutableListNodeinterface methods
Visualization
Tap to expand
Understanding the Visualization
1
The Problem
You have an audio guide that only plays forward, but you want to hear exhibits in reverse order
2
Brute Force
Count all exhibits, then for each position from end to start, walk through the entire guide to reach that exhibit
3
Stack Method
Walk through once taking notes on all exhibits, then read your notes backwards
4
Recursion Magic
Send friends ahead - each friend goes to the next exhibit, and they tell you about exhibits in reverse as they return
Key Takeaway
๐ฏ Key Insight: Recursion's natural LIFO behavior through the call stack automatically reverses the order - the last recursive call returns first, creating perfect reverse order output!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code