In: Computer Science
Reverse the contents of a stack using only stack operations [ push() and pop() ].
Using the java and give the explanation
By using two stack we can reverse stack contents.
For that what I have done is poping element from one stack and pushing that element into another stack.
Stack.java
//This implementation is using a linked list
import java.util.*;
public class Stack{
   Node head = null;
   //class node
   class Node{
       int data;
       Node next;
       //Node constructor
       Node(int d){
           this.data =
d;
           this.next =
null;
       }
   }
   //Method for pushing an element into stack
   public void push(Stack stack,int data){
       Node newNode = new
Node(data);
       if(head==null){
           stack.head =
newNode;
       }
       else{
           Node temp =
stack.head;
           stack.head =
newNode;
           newNode.next =
temp;
       }
   }
   //Method for removing top most element from the
stack
   public int pop(){
       int element = -1;
       if(head == null){
          
System.out.println("Stack is empty");
       }
       else{
           element =
head.data;
           head =
head.next;
          
       }
       return element;
   }
   //Method for traversing the stack
   public void traverse(Stack stack){
       Node temp = stack.head;
       while(temp!=null){
          
System.out.print(temp.data+"\t");
           temp =
temp.next;
       }
   }
   //Method for reversing stack
   public void reverse(Stack stack1){
       //Here what i am doing is removing
one element from one stack and adding it to the another one
       Stack stack2 = new Stack();//New
stack object
       while(stack1.head!=null){
          
stack2.push(stack2,stack1.pop());
       }
       System.out.println("\nStack after
Reverse");
       stack2.traverse(stack2);
   }
  
   public static void main(String[] args) {
       Stack stack1 = new Stack();
       System.out.print("Enter no.of
elements to be inserted into stack:");
       Scanner scan = new
Scanner(System.in);
       int n = scan.nextInt();
       for(int i=0;i<n;i++){
          
System.out.print("Enter an element:");
           int data =
scan.nextInt();
          
stack1.push(stack1,data);
       }
      
      
//System.out.println(stack1.pop());
       System.out.println("Stack before
reverse");
       stack1.traverse(stack1);
       stack1.reverse(stack1);
   }
}
Sample input and output:
