688. Print Immutable Linked List in Reverse

Given an ImmutableLinkedListNode interface with the following methods:

  • void printValue(): Prints the value of the node.
  • ImmutableLinkedListNode getNext(): Returns the next node in the list.

Implement a function printLinkedListInReverse that prints the linked list in reverse order.

Example 1:

Input: head = [1,2,3,4]

Output: [4,3,2,1]

Explanation:

The linked list is given in order: 1 → 2 → 3 → 4.

We need to print the elements in reverse order.

The reversed list is [4,3,2,1].

Example 2:

Input: head = [0,-4,-1,3,-5]

Output: [-5,3,-1,-4,0]

Explanation:

The original linked list: 0 → -4 → -1 → 3 → -5.

Reversing the list, we get -5 → 3 → -1 → -4 → 0.

This gives us the output [-5,3,-1,-4,0].

Now Your Turn!

Pick the correct output for the given input

Input: head = [-2,0,6,4,4,-6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The length of the linked list is between [1,1000].
  • The value of each node in the linked list is between [-1000,1000].

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* // 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) {
//Your Code Goes Here
}
};
Test Case

Input:

Head