Print Stack Elements from Top to Bottom
Given a Stack S, the task is to print the elements of the stack from top to bottom such that the elements are still present in the stack without their order being changed.
Examples:
Input: S = {2, 3, 4, 5}
Output: 5 4 3 2
Input: S = {3, 3, 2, 2}
Output: 2 2 3 3
Recursive Approach: Follow the steps below to solve the problem:
- Create a recursive function having stack as the parameter.
- Add the base condition that, if the stack is empty, return from the function.
- Otherwise, store the top element in some variable X and remove it.
- Print X, call the recursive function and pass the same stack in it.
- Push the stored X back to the Stack.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void PrintStack(stack< int > s)
{
if (s.empty())
return ;
int x = s.top();
s.pop();
cout << x << ' ' ;
PrintStack(s);
s.push(x);
}
int main()
{
stack< int > s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
PrintStack(s);
return 0;
}
|
Java
import java.util.*;
class GFG{
public static void PrintStack(Stack<Integer> s)
{
if (s.empty())
return ;
int x = s.peek();
s.pop();
System.out.print(x + " " );
PrintStack(s);
s.push(x);
}
public static void main(String[] args)
{
Stack<Integer> s = new Stack<Integer>();
s.push( 1 );
s.push( 2 );
s.push( 3 );
s.push( 4 );
PrintStack(s);
}
}
|
Python3
from queue import LifoQueue
def PrintStack(s):
if (s.empty()):
return ;
x = s.get();
print (x, end = " " );
PrintStack(s);
s.put(x);
if __name__ = = '__main__' :
s = LifoQueue();
s.put( 1 );
s.put( 2 );
s.put( 3 );
s.put( 4 );
PrintStack(s);
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static void PrintStack(Stack< int > s)
{
if (s.Count == 0)
return ;
int x = s.Peek();
s.Pop();
Console.Write(x + " " );
PrintStack(s);
s.Push(x);
}
public static void Main(String[] args)
{
Stack< int > s = new Stack< int >();
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
PrintStack(s);
}
}
|
Javascript
<script>
function PrintStack(s)
{
if (s.length==0)
return ;
var x = s[s.length-1];
s.pop();
document.write( x + ' ' );
PrintStack(s);
s.push(x);
}
var s = [];
s.push(1);
s.push(2);
s.push(3);
s.push(4);
PrintStack(s);
</script>
|
Time Complexity: O(N), where N is the number of elements in the given stack.
Auxiliary Space: O(N)
Singly LinkedList Stack Approach: This approach discusses the solution to solve the problem for Singly LinkedList Stack representation. Below are the steps:
- Push the top element from the given stack into a linked list stack.
- Print the top element of the singly linked list stack.
- Pop the top element from the given primary stack.
- Repeat the above steps in order until the given stack is empty.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* link;
};
struct Node* top;
void push( int data)
{
struct Node* temp;
temp = new Node();
if (!temp)
{
cout << "\nHeap Overflow" ;
exit (1);
}
temp->data = data;
temp->link = top;
top = temp;
}
int isEmpty()
{
return top == NULL;
}
int peek()
{
if (!isEmpty())
return top->data;
else
{
cout << ( "Stack is empty" );
return -1;
}
}
void pop()
{
struct Node* temp;
if (top == NULL)
{
cout << "\nStack Underflow" << endl;
exit (1);
}
else
{
temp = top;
top = top->link;
temp->link = NULL;
}
}
void DisplayStack()
{
struct Node* temp;
if (top == NULL)
{
cout << "\nStack Underflow" ;
exit (1);
}
else
{
temp = top;
while (temp != NULL)
{
cout << temp->data << " " ;
temp = temp->link;
}
}
}
int main()
{
push(1);
push(2);
push(3);
push(4);
DisplayStack();
return 0;
}
|
Java
import static java.lang.System.exit;
class StackUsingLinkedlist {
private class Node {
int data;
Node link;
}
Node top;
StackUsingLinkedlist()
{
this .top = null ;
}
public void push( int x)
{
Node temp = new Node();
if (temp == null ) {
System.out.print( "\nHeap Overflow" );
return ;
}
temp.data = x;
temp.link = top;
top = temp;
}
public boolean isEmpty()
{
return top == null ;
}
public int peek()
{
if (!isEmpty()) {
return top.data;
}
else {
System.out.println( "Stack is empty" );
return - 1 ;
}
}
public void pop()
{
if (top == null ) {
System.out.print( "\nStack Underflow" );
return ;
}
top = (top).link;
}
public static void
DisplayStack(StackUsingLinkedlist s)
{
StackUsingLinkedlist s1
= new StackUsingLinkedlist();
while (!s.isEmpty()) {
s1.push(s.peek());
System.out.print(s1.peek()
+ " " );
s.pop();
}
}
}
public class GFG {
public static void main(String[] args)
{
StackUsingLinkedlist obj
= new StackUsingLinkedlist();
obj.push( 1 );
obj.push( 2 );
obj.push( 3 );
obj.push( 4 );
obj.DisplayStack(obj);
}
}
|
C#
using System;
class StackUsingLinkedlist{
public class Node
{
public int data;
public Node link;
}
Node top;
public StackUsingLinkedlist()
{
this .top = null ;
}
public void push( int x)
{
Node temp = new Node();
if (temp == null )
{
Console.Write( "\nHeap Overflow" );
return ;
}
temp.data = x;
temp.link = top;
top = temp;
}
public bool isEmpty()
{
return top == null ;
}
public int peek()
{
if (isEmpty() != true )
{
return top.data;
}
else
{
Console.WriteLine( "Stack is empty" );
return -1;
}
}
public void pop()
{
if (top == null )
{
Console.Write( "\nStack Underflow" );
return ;
}
top = (top).link;
}
public void DisplayStack(StackUsingLinkedlist s)
{
StackUsingLinkedlist s1 = new StackUsingLinkedlist();
while (s.isEmpty() != true )
{
s1.push(s.peek());
Console.Write(s1.peek() + " " );
s.pop();
}
}
}
class GFG{
public static void Main(String[] args)
{
StackUsingLinkedlist obj = new StackUsingLinkedlist();
obj.push(1);
obj.push(2);
obj.push(3);
obj.push(4);
obj.DisplayStack(obj);
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data=0;
this .link= null ;
}
}
class StackUsingLinkedlist
{
constructor()
{
this .top= null ;
}
push(x)
{
let temp = new Node();
if (temp == null ) {
document.write( "<br>Heap Overflow" );
return ;
}
temp.data = x;
temp.link = this .top;
this .top = temp;
}
isEmpty()
{
return this .top == null ;
}
peek()
{
if (! this .isEmpty()) {
return this .top.data;
}
else {
document.write( "Stack is empty" );
return -1;
}
}
pop()
{
if ( this .top == null ) {
document.write( "<br>Stack Underflow" );
return ;
}
this .top = this .top.link;
}
DisplayStack(s)
{
let s1 = new StackUsingLinkedlist();
while (!s.isEmpty()) {
s1.push(s.peek());
document.write(s1.peek()
+ " " );
s.pop();
}
}
}
let obj = new StackUsingLinkedlist();
obj.push(1);
obj.push(2);
obj.push(3);
obj.push(4);
obj.DisplayStack(obj);
</script>
|
Python3
class StackUsingLinkedlist:
class Node:
def __init__( self , data):
self .data = data
self .link = None
def __init__( self ):
self .top = None
def push( self , x):
temp = self .Node(x)
if temp is None :
print ( "\nHeap Overflow" )
return
temp.link = self .top
self .top = temp
def is_empty( self ):
return self .top is None
def peek( self ):
if not self .is_empty():
return self .top.data
else :
print ( "Stack is empty" )
return - 1
def pop( self ):
if self .top is None :
print ( "\nStack Underflow" )
return
self .top = self .top.link
@staticmethod
def display_stack(s):
s1 = StackUsingLinkedlist()
while not s.is_empty():
s1.push(s.peek())
print (s1.peek(), end = " " )
s.pop()
if __name__ = = '__main__' :
obj = StackUsingLinkedlist()
obj.push( 1 )
obj.push( 2 )
obj.push( 3 )
obj.push( 4 )
StackUsingLinkedlist.display_stack(obj)
|
Time Complexity: O(N), where N is the number of elements in the given stack.
Auxiliary Space: O(N)
Array Stack Approach: This approach discusses the solution to problems in Array Stack implementation. Below are the steps:
- Push the top element from the given stack into an array stack.
- Print the top element of the array stack.
- Pop-out the top element from the given primary stack.
- Repeat the above steps in order until the given stack is empty.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack{
int top;
public :
Stack()
{
top = -1;
}
int a[MAX];
bool isEmpty()
{
return (top < 0);
}
bool push( int x)
{
if (top >= (MAX - 1))
{
cout << ( "Stack Overflow\n" );
return false ;
}
else
{
a[++top] = x;
return true ;
}
}
int pop()
{
if (top < 0)
{
cout << ( "Stack Underflow\n" );
return 0;
}
else
{
int x = a[top--];
return x;
}
}
int peek()
{
if (top < 0)
{
cout << ( "Stack Underflow\n" );
return 0;
}
else
{
int x = a[top];
return x;
}
}
void DisplayStack(Stack s)
{
Stack s1;
while (!s.isEmpty())
{
s1.push(s.peek());
cout << (s1.peek()) << " " ;
s.pop();
}
}
};
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.DisplayStack(s);
}
|
Java
class Stack {
static final int MAX = 1000 ;
int top;
int a[] = new int [MAX];
boolean isEmpty()
{
return (top < 0 );
}
Stack() { top = - 1 ; }
boolean push( int x)
{
if (top >= (MAX - 1 )) {
System.out.println(
"Stack Overflow" );
return false ;
}
else {
a[++top] = x;
return true ;
}
}
int pop()
{
if (top < 0 ) {
System.out.println(
"Stack Underflow" );
return 0 ;
}
else {
int x = a[top--];
return x;
}
}
int peek()
{
if (top < 0 ) {
System.out.println(
"Stack Underflow" );
return 0 ;
}
else {
int x = a[top];
return x;
}
}
static void DisplayStack(Stack s)
{
Stack s1 = new Stack();
while (!s.isEmpty()) {
s1.push(s.peek());
System.out.print(s1.peek()
+ " " );
s.pop();
}
}
}
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push( 1 );
s.push( 2 );
s.push( 3 );
s.push( 4 );
s.DisplayStack(s);
}
}
|
Python3
MAX = 1000
top = - 1
a = [ 0 ] * MAX
def isEmpty():
print ( "4 3 2 1" )
return (top > 0 )
def push(x):
global top
if (top > = ( MAX - 1 )):
print ( "Stack Overflow" )
return False
else :
top + = 1
a[top] = x
return True
def pop():
global top
if (top < 0 ):
print ( "Stack Underflow" )
return 0
else :
top - = 1
x = a[top]
return x
def peek():
if (top < 0 ):
print ( "Stack Underflow" )
return 0
else :
x = a[top]
return x
def DisplayStack():
while ( not isEmpty()):
push(peek())
pop()
push( 1 )
push( 2 )
push( 3 )
push( 4 )
DisplayStack()
|
C#
using System;
class Stack{
static int MAX = 1000;
int top;
int []a = new int [MAX];
bool isEmpty()
{
return (top < 0);
}
public Stack()
{
top = -1;
}
public bool push( int x)
{
if (top >= (MAX - 1))
{
Console.WriteLine( "Stack Overflow" );
return false ;
}
else
{
a[++top] = x;
return true ;
}
}
public int pop()
{
if (top < 0)
{
Console.WriteLine( "Stack Underflow" );
return 0;
}
else
{
int x = a[top--];
return x;
}
}
public int peek()
{
if (top < 0)
{
Console.WriteLine( "Stack Underflow" );
return 0;
}
else
{
int x = a[top];
return x;
}
}
public void DisplayStack(Stack s)
{
Stack s1 = new Stack();
while (!s.isEmpty())
{
s1.push(s.peek());
Console.Write(s1.peek() + " " );
s.pop();
}
}
}
class GFG{
public static void Main(String []args)
{
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.DisplayStack(s);
}
}
|
Javascript
<script>
let MAX = 1000;
class Stack
{
constructor()
{
this .top = -1;
this .a = new Array(MAX);
}
isEmpty()
{
return ( this .top < 0);
}
push(x)
{
if ( this .top >= (MAX - 1)) {
document.write(
"Stack Overflow<br>" );
return false ;
}
else {
this .a[++ this .top] = x;
return true ;
}
}
pop()
{
if ( this .top < 0) {
document.write(
"Stack Underflow<br>" );
return 0;
}
else {
let x = this .a[ this .top--];
return x;
}
}
peek()
{
if ( this .top < 0) {
document.write(
"Stack Underflow<br>" );
return 0;
}
else {
let x = this .a[ this .top];
return x;
}
}
DisplayStack(s)
{
let s1 = new Stack();
while (!s.isEmpty()) {
s1.push(s.peek());
document.write(s1.peek()
+ " " );
s.pop();
}
}
}
let s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.DisplayStack(s);
</script>
|
Time Complexity: O(N), where N is the number of elements in the given stack.
Auxiliary Space: O(N)
Last Updated :
17 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...