Interview Question – Stack

Given a stack containing n elements reverse the stack with the help of an empty stack.





import java.util.Stack;

public class StackReversal {
	public static void reverseStack(Stack<Integer> stack) {
		if (stack.empty())
			return;
		int temp = stack.pop();
		reverseStack(stack); // popping the elemnt of stack
		insertAtBottom(stack, temp);

	}

	public static void print(Stack<Integer> stack) {
		for (int i = 0; i < stack.size(); i++) {
			System.out.print(stack.get(i) + " ");

		}

	}

	public static void insertAtBottom(Stack<Integer> stack, int data) {
		if (stack.isEmpty()) {
			stack.push(data);
			return;
		}
		int temp = stack.pop();
		insertAtBottom(stack, data);
		stack.push(temp);
	}

	public static void main(String args[]) {
		Stack<Integer> stack = new Stack();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		reverseStack(stack);
		print(stack); // printing the element

	}

}

Thanks and Regards,
Solution provided by Nilmani Prashanth

About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *