Print Stack in reverse order.

Objective: Given a stack, write a program to print the stack elements in reverse order.

Example:

Approach:

Use Temporary stack:

Take temporary stack, and copy all the items from the given stack to a temporary stack. Elements will be stored in a temporary stack in reverse order. Now print elements from the temporary stack and while printing, restore all the elements to the originally given array.

Code:


Output:

4 9 6 8 10 5

Use Recursion

Pop the top element from the stack and make a recursive call till the stack is not empty. This will store all the stack elements into function stack in reverse stack. In tail recursion print the elements and restore elements in the originally given array.

Code:

Output:

4 9 6 8 10 5

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: