mxllcf

导航

栈和队列

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/solution/

(用两个栈实现队列)

 

使用一个栈作为插入,一个栈用作删除,

删除时,先判断第二个栈内有没有元素,如果有就直接弹出,如果没有就先从栈1中弹出所有元素到第二个栈中。如果第一个栈也没有,那就返回-1.

 

 

注意:

如果你使用Stack的方式来做这道题,会造成速度较慢; 原因的话是Stack继承了Vector接口,而Vector底层是一个Object[]数组,那么就要考虑空间扩容和移位的问题了。 可以使用LinkedList来做Stack的容器,因为LinkedList实现了Deque接口,所以Stack能做的事LinkedList都能做,其本身结构是个双向链表,扩容消耗少。

 

class CQueue {
    LinkedList<Integer> stack1;
    LinkedList<Integer> stack2;
    public CQueue() {
        stack1 = new LinkedList<>();
        stack2 = new LinkedList<>();
    }
    
    public void appendTail(int value) {
        stack1.add(value);
    }
    
    public int deleteHead() {
        if (stack2.isEmpty()) {
            if (stack1.isEmpty()) return -1;
            while(!stack1.isEmpty()) {
                stack2.add(stack1.pop());
            }
            return stack2.pop();
        }else return stack2.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

 

 

 

https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/(维护一个最小栈)

class MinStack {

    /** initialize your data structure here. */

    LinkedList<Integer> stack1;
    LinkedList<Integer> stack2;
    public MinStack() {
        stack1 = new LinkedList<>();
        stack2 = new LinkedList<>();

    }
    

    public void push(int x) {
        stack1.addLast(x);
        if (stack2.isEmpty() || x <= stack2.peekLast()) {
            stack2.addLast(x);
        }
    }
    
 
    public void pop() {
        if(stack1.pollLast().equals(stack2.peekLast()))
            stack2.pollLast();
       
    }
    
    public int top() {
        return stack1.peekLast();
    }
    
    public int min() {
        return stack2.peekLast();
    }
}



/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.min();
 */

 

 

posted on 2021-11-01 18:14  mxllcf  阅读(23)  评论(0编辑  收藏  举报