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

import java.util.Objects;
import java.util.Stack;

class Solution {


    private Stack<Integer> secondStack = new Stack<>();

    public void sort(Stack<Integer> stack) {

        if (Objects.isNull(stack) || stack.isEmpty()) {
            return;
        }

        while (! stack.isEmpty()) {
            int a = stack.pop();
            while (! secondStack.isEmpty() && a < secondStack.peek()) {
                stack.push(secondStack.pop());
            }
            secondStack.push(a);
        }

        while (! secondStack.isEmpty()) {
            stack.push(secondStack.pop());
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章