top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: How to sort a Stack using a temporary Stack?

0 votes
480 views
Java: How to sort a Stack using a temporary Stack?
posted Mar 23, 2016 by Joyce

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Try this method to sort stack where I have used "tempStack" as a temporary stack.

 public static Stack<Integer> sortStack(Stack<Integer> inputStack){
        Stack<Integer> tempStack = new Stack<Integer>();
        while(!inputStack.isEmpty()) {
            int temp = inputStack.pop();
            while(!tempStack.isEmpty() && tempStack.peek() > temp) {
                inputStack.push(tempStack.pop());
            }
            tempStack.push(temp);
        }
        return tempStack;
    }
answer Mar 23, 2016 by Shivam Kumar Pandey
...