Advertisement
javatechie

Reverse Stack

Sep 4th, 2020
1,517
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.74 KB | None | 0 0
  1. package com;
  2.  
  3. import java.util.Stack;
  4.  
  5. public class StackReverse {
  6.  
  7.     public static void reverse(Stack<Integer> stack) {
  8.  
  9.         Stack<Integer> temporaryStack = new Stack<>();
  10.  
  11.         //copy all the elements from given stack to temporary stack
  12.         while(stack.size()>0){
  13.             temporaryStack.push(stack.pop());
  14.         }
  15.  
  16.         while(temporaryStack.size()>0){
  17.             int x = temporaryStack.pop();
  18.             System.out.print(x + " ");
  19.             stack.push(x);
  20.         }
  21.     }
  22.  
  23.     public static void main(String[] args) {
  24.         Stack<Integer> stack = new Stack<>();
  25.         stack.push(10);
  26.         stack.push(20);
  27.         stack.push(30);
  28.         stack.push(40);
  29.  
  30.  
  31.         reverse(stack);
  32.  
  33.     }
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement