11.用一個棧實現另一個棧的排序

【題目】

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

【代碼】

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