Sort An Unsorted Stack

Given a stack of integers, sort it in ascending order using another temporary stack.

Examples:

Input : [34, 3, 31, 98, 92, 23]
Output : [3, 23, 31, 34, 92, 98]

Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8]


经典题,这道题的套路是创建一个temp stack 用于元素的存取

    public Stack<Integer> sortstack(Stack<Integer> input){
        if(input == null){
            return null;
        }
        Stack<Integer> tempStack = new Stack<>();
        
        while(!input.isEmpty()){
            int temp = input.pop();
            while(!tempStack.isEmpty() && tempStack.peek() > temp){
                input.push(tempStack.pop());
            }
            tempStack.push(temp);
        }
        return tempStack;
    }


猜你喜欢

转载自www.cnblogs.com/incrediblechangshuo/p/9049307.html