Wednesday, December 2, 2015

Sort a Stack using one additional Stack

    public Stack<Integer> SortStack(Stack<Integer> input)    {
        if(input.isEmpty())    return input;
        Stack<Integer> buffer = new Stack<Integer>(); //Buffer Stack
        while(!input.isEmpty())    {
            int temp = input.pop();
            if(!buffer.isEmpty() && temp<buffer.peek())
                input.push(buffer.pop());
            buffer.push(temp);
        }
        return buffer;
    }



This Code doesn't work all the time
Input: [5, 7, 8, 9, 6, 0, 2]
Output: [0, 2, 6, 8, 7, 5, 9]

No comments:

Post a Comment

UA-39217154-2