[LeetCode] Print Immutable Linked List in Reverse

1265. Print Immutable Linked List in Reverse

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* // This is the ImmutableListNode's API interface.
* // You should not implement it, or speculate about its implementation.
* class ImmutableListNode {
* public:
* void printValue(); // print the value of the node.
* ImmutableListNode* getNext(); // return the next node.
* };
*/

class Solution {
public:
void printLinkedListInReverse(ImmutableListNode* head) {
if(!head) return;
printLinkedListInReverse(head->getNext());
head->printValue();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/11/PS/LeetCode/print-immutable-linked-list-in-reverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.