1.3 栈(3)


套路

  • 暂无

注意点

  • Stack : empty() ,ArrayDeque / LinkedList:isEmpty()
  • poll()、top()、peek()、min()操作都需要排除栈为空的情况 !stack.empty()

目录

  • 包含min函数的栈
  • 栈的压入、弹出序列(实际过程模拟还需要练习)
  • 用两个栈实现队列

包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

Stack<Integer> stack = new Stack<>();
Stack<Integer> stackMin = new Stack<>();

public void push(int node) {
    stack.push(node);
    if (stackMin.empty()) {
        stackMin.push(node);
    } else if (node <= stackMin.peek()) {
        stackMin.push(node);
    }
}

public void pop() {
    if (stack.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        if (stack.pop() == stackMin.peek()) {
            stackMin.pop();
        }
    }
}

public int top() {
    if (stack.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        return stack.peek();
    }
}

public int min() {
    if (stackMin.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        return stackMin.peek();
    }
}

栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

public boolean IsPopOrder(int [] pushA,int [] popA) {
    if (pushA == null || popA == null || pushA.length != popA.length) {
        return false;
    }
    Stack<Integer> stack = new Stack<>();
    int popIndex = 0;
    for (int i = 0; i < pushA.length; i++) {
        stack.push(pushA[i]);
        while (!stack.empty() && stack.peek() == popA[popIndex]) {
            stack.pop();
            popIndex++;
        }
    }
    return stack.empty();
}

用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

  • 解题思路:在将栈1中的元素放入栈2时,只要保证栈2此时为空,就可以保证正确性。
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
    stack1.push(node);
}

public int pop() {
    if (stack1.empty() && stack2.empty()) {
        return -1;
    }
    if (stack2.empty()) {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容