Print Immutable Linked List in Reverse Problem
Description
LeetCode Problem 1265.
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.
Example 1:
Input: head = [1,2,3,4]
Output: [4,3,2,1]
Example 2:
Input: head = [0,-4,-1,3,-5]
Output: [-5,3,-1,-4,0]
Example 3:
Input: head = [-2,0,6,4,4,-6]
Output: [-6,4,4,6,0,-2]
Constraints:
- The length of the linked list is between
[1, 1000]. - The value of each node in the linked list is between
[-1000, 1000].
Follow up:
Could you solve this problem in:
- Constant space complexity?
- Linear time complexity and less than linear space complexity?
Solution
Approach: Recursion
We cannot change the list or walk it backwards, but recursion gives us the reverse order for free. To print the list starting at head in reverse:
- first print the rest of the list (starting at
head.getNext()) in reverse, - then print
headitself.
The empty list (head is null) prints nothing and ends the recursion. The calls go all the way to the last node before anything is printed, and the values come out as the calls return, last node first. The call stack is doing the work of an explicit stack of nodes. With at most 1000 nodes, the recursion depth is safe in every language.
For the follow-ups: constant space is possible by walking to the last unprinted node from the head every time, in O(n2) time. Splitting the list into about √n blocks, remembering the first node of each, and printing one block at a time with a small stack gives O(n) time with O(√n) space.
Complexity: O(n) time and O(n) space for the recursion, where n is the length of the list.
class Solution:
def printLinkedListInReverse(self, head: "ImmutableListNode") -> None:
# Print the rest of the list first, then this node: the recursion stack holds the nodes for us.
if head is not None:
self.printLinkedListInReverse(head.getNext())
head.printValue()