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.
The problem restricts us to only use the provided ImmutableListNode interface, which allows us to print the value and get the next node, but not to modify the list or access its value directly. To print the list in reverse, we can use recursion (which uses the call stack) or an explicit stack. For the follow-up, a block-reversal approach can achieve O(1) space, but recursion is the most straightforward.
We traverse the list recursively to the end starting from head, then print the value on the way back. This prints the values in reverse order. This uses O(n) space due to the call stack. For O(1) space, we can use a block-reversal technique, but it’s more complex and rarely required in interviews.
// The ImmutableListNode interface is provided by the problem:
// class ImmutableListNode {
// public:
// void printValue() const; // print the value of this node.
// ImmutableListNode* getNext() const; // return the next node.
// };
voidprintLinkedListInReverse(const ImmutableListNode* head) {
if (!head) return;
printLinkedListInReverse(head->getNext());
head->printValue();
}
// 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.// }classSolution {
publicvoidprintLinkedListInReverse(ImmutableListNode head) {
if (head ==null) return;
printLinkedListInReverse(head.getNext());
head.printValue();
}
}
1
2
3
4
5
6
7
8
9
// interface ImmutableListNode {
// fun printValue()
// fun getNext(): ImmutableListNode?
// }
funprintLinkedListInReverse(head: ImmutableListNode?) {
if (head ==null) return printLinkedListInReverse(head.getNext())
head.printValue()
}
1
2
3
4
5
6
7
8
9
10
# """# class ImmutableListNode:# def printValue(self) -> None: ...# def getNext(self) -> 'ImmutableListNode': ...# """defprintLinkedListInReverse(head: 'ImmutableListNode') ->None:
if head isNone:
return printLinkedListInReverse(head.getNext())
head.printValue()