04-03.棧的逆序

題目

一個棧中的元素爲整型,現在想將改棧從頂到低按從大到小的順序排序,只能申請一個棧。除此之外,可以申請新的變量,但不能申請額外的數據結構,如何完成排序

代碼

    public static void sortStack(Stack<Integer> stack) {
        Stack<Integer> help = new Stack<>();
        while (!stack.isEmpty()) {
            int currentNum = stack.pop();
            while (!help.isEmpty() && help.peek() > currentNum) {
                stack.push(help.pop());
            }
            help.push(currentNum);
        }
        while (!help.isEmpty()) {
            stack.push(help.pop());
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章