Print Stack Elements from Top to Bottom

Soumya Agrawal
Last Updated: May 13, 2022

Introduction

Do you know about stacks? Before discussing the problem, let’s brush up on your knowledge about stacks. Stack is a commonly used linear data structure that behaves like a real-world stack, for example, a deck of cards. Stack follows the LIFO principle(Last In First Out), which allows all data operations at one end only. 

In the LIFO principle, the element which is placed at last is accessed first. Basic operations of the stack are Push()- pushing an element on the stack and Pop()- removing an element from the stack.

 

We will see different approaches to print stack elements from top to bottom based on the LIFO principle.

 

Without any delays, let’s get started.

Problem Statement

 

We will be given a stack, and we aim to print the elements of the stack from top to bottom such that the order of the elements is not changed.

Let me explain to you with a quick example.

 

Input

 

 

 

Output

4 3 2 1

Explanation

First, ‘1’ will be inserted into the stack.
After this, element ‘2’ will be inserted into the stack.
After this, element ‘3’ will be inserted into the stack.
After this, element ‘4’ will be inserted into the stack.

‘4’ will be the top element of the stack and the first one to be printed.

Approach 1: Array Stack

The first approach we will be using to solve this problem is array stack. Arrays are not dynamic in nature, but it is easy to implement.

  1. We will be creating an array for storing the stack elements.
  2. Push the top element from the stack to that array.
  3. Print the top element of the array stack.
  4. Pop out the element from the given stack.
  5. Repeat the above steps.

Implementation

 

CODE IN JAVA

class Stack {

	static final int MAX = 1000;

	// Stores the index where element
	// needs to be inserted
	int top;

	// Array stack
	int arr[] = new int[MAX];

	// Function to check whether array is empty or not
	boolean isEmpty()
	{
		return (top < 0);
	}

	// Constructor
	Stack() { 
		top = -1; 
	}

	// Function that pushes the element
	// to the top of the stack
	boolean push(int s)
	{
		// If stack is full
		if (top >= (MAX - 1)) {
			System.out.println("Stack Overflow");
			return false;
		}
		else {
			arr[++top] = s;
			return true;
		}
	}

	// Function that removes the top
	// element from the stack
	int pop()
	{
		// If stack is empty
		if (top < 0) {
			System.out.println("Stack Underflow");
			return 0;
		}

		else {
			int s = arr[top--];
			return s;
		}
	}

	// To get the top element
	int peek()
	{
		// If stack is empty
		if (top < 0) {
			System.out.println("Stack Underflow");
			return 0;
		}

		else {
			int s = arr[top];
			return s;
		}
	}

	// To print the elements of the stack
	static void display(Stack s) {
		// Create another stack
		Stack s1 = new Stack();

		// Until stack is empty
		while (!s.isEmpty()) {
			s1.push(s.peek());
			// Print the element
			System.out.print(s1.peek() + " ");
			s.pop();
		}
	}
}

// Driver Code
class Main {

	// Main function
	public static void main(String args[])
	{
		Stack s = new Stack();

		// Given stack
		s.push(1);
		s.push(2);
		s.push(3);
		s.push(4);

		// Function Call
		s.display(s);
	}
}

 

CODE IN C++

#include <bits/stdc++.h>
using namespace std;
#define MAX 100000
 
class Stack{

	int top;
 
	public:
 
    	Stack() {
        	top = -1;
    	}
     
    	// Array for storing the stack elements
    	int arr[MAX];
     
    	// Function to check if the stack is empty or not
    	bool isEmpty() {
        	return (top < 0);
    	}
 
    	// Function to pushes the element to the top
    	bool push(int x) {
         
        	if (top >= (MAX - 1)) {
            	cout << ("Stack Overflow\n");
            	return false;
        	}
 
        	// Insert the element x
        	else {
            	arr[++top] = x;
            	return true;
        	}
    	}
 
    	// Function to removes the top element
    	int pop() {
         
        	if (top < 0) {
            	cout << ("Stack Underflow\n");
            	return 0;
        	}
 
        	// Remove the element
        	else {
            	int x = arr[top--];
            	return x;
        	}
    	}
 
    	// Function for getting the top element
    	int peek() {
         
        	if (top < 0) {
            	cout << ("Stack Underflow\n");
            	return 0;
        	}
 
        	// Reading the top element
        	else {
            	int x = arr[top];
            	return x;
        	}
    	}
 
    	// Function to print and restore the stack
    	void DisplayStack(Stack s) {
         
        	Stack s1;
         
        	while (!s.isEmpty()) {
            	s1.push(s.peek());
             
            	// Print the elements
            	cout << (s1.peek()) << " ";
            	s.pop();
        	}
    	}
};
 
// Driver Code
int main()
{
    Stack s;
     
    // The given stack
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
 
    s.DisplayStack(s);
}

 

CODE IN PYTHON

MAX = 1000
 
# Pointer to th top of stack
top = -1
 
# Empty Array for storing elements
a = [0]*MAX
 
# Function to check
# if stack is empty or not
def isEmpty():
 return (top >= 0)
 
# Function that pushes the element to the top of the stack
def push(x):
  
 global top
 # Check if stack is full
 if (top >= (MAX - 1)):
   print("Stack Overflow")
   return False
 
 # Otherwise insert the element x
 else:
   top+=1
   a[top] = x
   return True
 
# Function that removes the top element from the stack
def pop():
 global top
 # If stack is empty
 if (top < 0):
   print("Stack Underflow")
   return 0
 
 # Otherwise remove element
 else:
   top-=1
   x = a[top]
   return x
 
# Function to get the top element
def peek():
 # If stack is empty
 if (top < 0):
   print("Stack Underflow")
   return 0
 
 # Otherwise remove element
 else:
   x = a[top]
   return x
 
# Function to print the elements
# and restore the stack

def DisplayStack():
 # Until stack is empty
 x = peek()
 while (x):
   # Print the element
   print(x, end = " ")
   x = pop()
 
# Given stack
push(1)
push(2)
push(3)
push(4)

# Function Call
DisplayStack()

Output

4 3 2 1

 

Time Complexity: O(n), n=number of elements.

Space Complexity: O(n).

Approach 2

Recursive

 

We will use a function that will be recursive(calls itself) and print the elements of the stack from top to bottom.

 

  1. Declare a recursive function.
  2. Add a base condition to it; if the stack is empty, print return.
  3. Declare a variable that will store the top element and remove that element from the stack.
  4. Print the value of the variable and call the recursive function.
  5. Push that variable back into the stack to restore the stack as it was.

 

Implementation

 

CODE IN JAVA

import java.util.*;

class Solution{

	// To print the elements of the stack
	public static void Print(Stack<Integer> s)
	{

		// If stack is empty
		// Base condition
		if (s.empty())
		return;

		// To store the top element of the stack
		int t = s.peek();

		// Pop the top element
		s.pop();

		// Print the variable 't'
		System.out.print(t + " ");

		// Print the remaining stack
		PrintStack(s);

		// Push the element back to restore the stack
		s.push(t);
	}

	// Main function
	public static void main(String[] args)
	{
		Stack<Integer> s = new Stack<Integer>();

		// Given stack s
		s.push(1);
		s.push(2);
		s.push(3);
		s.push(4);

		// Recursive Function call
		Print(s);
	}
}

 

CODE IN C++

#include <bits/stdc++.h>
using namespace std;
 
// Function to print elements from top to bottom 
void PrintStack(stack<int> s)
{
    // If stack is empty
    if (s.empty())
        return;
 
	// Get the top of the stack
    int x = s.top();
 
    // Pop the top element
    s.pop();
 
    // Print the current top of the stack i.e., x
    cout << x << ' ';
 
    // Recursive Call
    PrintStack(s);
 
    // Push the element back
    s.push(x);
}
 
// Driver Code
int main()
{
    stack<int> s;
 
    // The given stack s
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);
 
    // Function Call
    PrintStack(s);
 
    return 0;
}

 

CODE IN PYTHON

from queue import LifoQueue
 
# Function to print stack elements from top to bottom with the order of elements unaltered
def PrintStack(s):
 
    # Check if stack is empty
    if (s.empty()):
        return;
 
    # Extract the top
    x = s.get();
 
    # Remove the top element
    #s.pop();
 
    # Print current top
    # of the stack i.e., x
    print(x, end = " ");
 
    # Recurse to print
    # remaining stack
    PrintStack(s);
 
    # Push the element
    # back
    s.put(x);
 
# Driver code
if __name__ == '__main__':
   
    s = LifoQueue();
 
    # Given stack s
    s.put(1);
    s.put(2);
    s.put(3);
    s.put(4);
 
    # Function call
    PrintStack(s);

Output

4 3 2 1 

 

Time Complexity: O(n), n=number of elements

Space Complexity: O(n).

FAQ’S

 

1). What do you mean by Stack data structure?

Stack is a linear data structure to store elements in order. It follows the LIFO principle(Last In First Out), which prints the last element inserted in the stack as the first element.

 

2). How many approaches are there to print elements of the stack from top to bottom?

There are three approaches to solve this problem:

  • Array Stack
  • Recursive
  • Singly LinkedList

 

3). What is the time complexity of the recursive approach?

Time Complexity is O(n), where n is the number of elements in the stack.

 

Key Takeaways

In this blog, we talked about stacks and, most importantly, how to print the elements from top to bottom such that elements are present in the stack without their order being changed. We have implemented the problem using two approaches in the Java language.

 

Building the foundation of any topic is necessary, so first, you should gain more knowledge on Stacks before heading into its problems.

 

You can use CodeStudio to practice various DSA questions typically asked in interviews. It will help you in mastering efficient coding techniques.

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think