Saturday 28 May 2016

Sort a stack using temporary stack


Stack is a data structure which is based on first-in ,last-out algorithm.It basically means the element which is added first will be removed at last.There are various ways available to sort the stack of which one of them is using temporary stack.

Sample Program:-


 import java.util.Stack;  
 /**  
  * @author Dixit  
  *  
  */  
 public class StackSorting {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Stack<Integer> stack = new Stack<Integer>();  
           stack.add(1);  
           stack.add(5);  
           stack.add(10);  
           stack.add(9);  
           stack.add(2);  
           Stack<Integer> tempStack = new Stack<Integer>();  
           while (!stack.isEmpty()) {  
                int value = stack.pop();  
                while (!tempStack.isEmpty() && tempStack.peek() > value) {  
                     stack.push(tempStack.pop());  
                }  
                tempStack.push(value);  
           }  
           for (int i = 0; i < tempStack.size(); i++) {  
                System.out.println(tempStack.get(i));  
           }  
      }  
 }  


Output:  
 1  
 2  
 5  
 9  
 10  



Enjoy Programming:)

No comments:

Post a Comment