Print Reverse a linked list using Stack
Last Updated :
06 Jan, 2023
Given a linked list, print the reverse of it without modifying the list.
Examples:
Input : 1 2 3 4 5 6
Output : 6 5 4 3 2 1
Input : 12 23 34 45 56 67 78
Output : 78 67 56 45 34 23 12
Below are different solutions that are now allowed here as we cannot use extra space and modify the list.
- Recursive solution to print reverse a linked list. Requires extra space.
- Reverse linked list and then print. This requires modifications to the original list.
- A O(n2) solution to print reverse of linked list that first count nodes and then prints k-th node from the end.
In this post, the efficient stack-based solution is discussed.
- First, insert all the elements in the stack
- Print stack till stack is not empty
Note: Instead of inserting data from each node into the stack, insert the node’s address onto the stack. This is because the size of the node’s data will be generally more than the size of the node’s address. Thus, the stack would end up requiring more memory if it directly stored the data elements. Also, we cannot insert the node’s data onto the stack if each node contained more than one data member. Hence, a simpler and efficient solution would be to simply insert the node’s address.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push( struct Node**head_ref, int new_data)
{
struct Node* new_node
= ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int getCount( struct Node* head)
{
int count = 0;
struct Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int getNth( struct Node* head, int n)
{
struct Node* curr = head;
for ( int i = 0; i < n - 1 && curr != NULL; i++)
curr = curr->next;
return curr->data;
}
void printReverse(Node* head)
{
stack<Node*> stk;
Node* ptr = head;
while (ptr != NULL) {
stk.push(ptr);
ptr = ptr->next;
}
while (!stk.empty()) {
cout << stk.top()->data << " " ;
stk.pop();
}
cout << "\n" ;
}
int main()
{
struct Node* head = NULL;
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printReverse(head);
return 0;
}
|
Java
import java.util.*;
class GFG {
static class Node {
int data;
Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
static int getCount(Node head)
{
int count = 0 ;
Node current = head;
while (current != null ) {
count++;
current = current.next;
}
return count;
}
static int getNth(Node head, int n)
{
Node curr = head;
for ( int i = 0 ; i < n - 1 && curr != null ; i++)
curr = curr.next;
return curr.data;
}
static void printReverse(Node head)
{
Stack<Node> stk = new Stack<Node>();
Node ptr = head;
while (ptr != null ) {
stk.push(ptr);
ptr = ptr.next;
}
while (stk.size() > 0 ) {
System.out.print(stk.peek().data + " " );
stk.pop();
}
System.out.println( "\n" );
}
public static void main(String args[])
{
Node head = null ;
head = push(head, 5 );
head = push(head, 4 );
head = push(head, 3 );
head = push(head, 2 );
head = push(head, 1 );
printReverse(head);
}
}
|
Python3
class Node:
def __init__( self , next = None , data = None ):
self . next = next
self .data = data
def push(head_ref, new_data):
new_node = Node()
new_node.data = new_data
new_node. next = (head_ref)
(head_ref) = new_node
return head_ref
def getCount(head):
count = 0
current = head
while (current ! = None ):
count = count + 1
current = current. next
return count
def getNth(head, n):
curr = head
i = 0
while (i < n - 1 and curr ! = None ):
curr = curr. next
i = i + 1
return curr.data
def printReverse(head):
stk = []
ptr = head
while (ptr ! = None ):
stk.append(ptr)
ptr = ptr. next
while ( len (stk) > 0 ):
print (stk[ - 1 ].data, end = " " )
stk.pop()
print ( " " )
head = None
head = push(head, 5 )
head = push(head, 4 )
head = push(head, 3 )
head = push(head, 2 )
head = push(head, 1 )
printReverse(head)
|
C#
using System;
using System.Collections.Generic;
class GFG {
public class Node {
public int data;
public Node next;
};
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
static int getCount(Node head)
{
int count = 0;
Node current = head;
while (current != null ) {
count++;
current = current.next;
}
return count;
}
static int getNth(Node head, int n)
{
Node curr = head;
for ( int i = 0; i < n - 1 && curr != null ; i++)
curr = curr.next;
return curr.data;
}
static void printReverse(Node head)
{
Stack<Node> stk = new Stack<Node>();
Node ptr = head;
while (ptr != null ) {
stk.Push(ptr);
ptr = ptr.next;
}
while (stk.Count > 0) {
Console.Write(stk.Peek().data + " " );
stk.Pop();
}
Console.WriteLine( "\n" );
}
public static void Main(String[] args)
{
Node head = null ;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
printReverse(head);
}
}
|
Javascript
<script>
class Node {
constructor()
{
this .data = 0;
this .next = null ;
}
};
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
function getCount(head)
{
var count = 0;
var current = head;
while (current != null ) {
count++;
current = current.next;
}
return count;
}
function getNth(head, n)
{
var curr = head;
for ( var i = 0; i < n - 1 && curr != null ; i++)
curr = curr.next;
return curr.data;
}
function printReverse(head)
{
var stk = [];
var ptr = head;
while (ptr != null ) {
stk.push(ptr);
ptr = ptr.next;
}
while (stk.length > 0) {
document.write(stk[stk.length-1].data + " " );
stk.pop();
}
document.write( "<br>" );
}
var head = null ;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
printReverse(head);
</script>
|
Time complexity: O(N) where N is number of nodes of linked list
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...