您的位置:首页 > 其它

用一个栈实现另一个栈的排序

2018-11-06 17:01 267 查看
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());
        }
    }
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  排序