Printing a linked list in reverse

Companies:
  • Adobe Interview Questions
  • Amazon Interview Questions
  • Oracle Interview Questions

Given a singly linked list, print the elements of the linked list in reverse without modifying the linked list

Example Test Cases

Sample Test Case 1

Input Array: [1 -> 2 -> 3]
Expected Output: 3, 2, 1

Solution

We can solve this problem easily by using recursion. The idea is to print the value of a node only after it’s subsequent’s node’s value is printed. If there are no subsequent nodes then print the value directly as shown in the code below.

Implementation

#include <iostream>
using namespace std;

typedef struct node {
	int value;
	node* next;
} node;

// Insert at the front of the linked list.
node* addNode(node* list, int value) {
	node* newNode = new node;
	newNode->value = value;
	newNode->next = list;
	return newNode;
}

void printInReverse(node* current) {
	if (current == NULL) {
		return;
	}
	else {
		printInReverse(current->next);
		cout << current->value << " ";
	}
}

int main() {
	node* head = addNode(NULL, 3);
	head = addNode(head, 2);
	head = addNode(head, 1);
	// This will create a linked list 1->2->3
	
	printInReverse(head);
	return 0;
}
[gravityforms id="5" description="false" titla="false" ajax="true"]