Print Immutable Linked List in Reverse in C++

Suppose we have an immutable linked list, we have to print out all values of each node in reverse with the help of the following interface −

  • ImmutableListNode − This is an interface of an immutable linked list, we are given the head of the list.

We have to use the following functions to access the linked list −

  • ImmutableListNode.printValue() − This will print value of the current node.

  • ImmutableListNode.getNext() −This will return the next node.

So if the list is like: [0, -4, -1, 3, -5], then the output will be [-5, 3, -1, -4, 0]

To solve this, we will follow these steps −

  • Define a stack st for ImmutableListNode type node

  • while the head is not null

    • insert the head into st

    • head := next of head

  • while st is not empty

    • print the value of stack top node

    • delete node from stack

Example (C++)

Let us see the following implementation to get a better understanding −

class Solution {
   void printLinkedListInReverse(ImmutableListNode* head) {
      stack <ImmutableListNode*> st;
         head = head->getNext();