VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-stack-elements-from-top-to-bottom/

⇱ Print Stack Elements from Top to Bottom - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Stack Elements from Top to Bottom

Last Updated : 15 Jul, 2025

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:

  1. Create a recursive function having stack as the parameter.
  2. Add the base condition that, if the stack is empty, return from the function.
  3. Otherwise, store the top element in some variable X and remove it.
  4. Print X, call the recursive function and pass the same stack in it.
  5. Push the stored X back to the Stack.

Below is the implementation of the above approach:


Output
4 3 2 1

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:

  1. Push the top element from the given stack into a linked list stack.
  2. Print the top element of the singly linked list stack.
  3. Pop the top element from the given primary stack.
  4. Repeat the above steps in order until the given stack is empty.

Below is the implementation of the above approach:


Output
4 3 2 1

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:

  1. Push the top element from the given stack into an array stack.
  2. Print the top element of the array stack.
  3. Pop-out the top element from the given primary stack.
  4. Repeat the above steps in order until the given stack is empty.

Below is the implementation of the above approach:


Output
4 3 2 1

Time Complexity: O(N), where N is the number of elements in the given stack.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: