1.3 栈(3)


套路

  • 暂无

注意点

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

目录

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

包含min函数的栈

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

Stack stack = new Stack<>();
Stack 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 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 stack1 = new Stack();
Stack stack2 = new Stack();

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();
}

你可能感兴趣的:(1.3 栈(3))