当前位置:网站首页>Sword finger offer day 1 stack and queue (simple)

Sword finger offer day 1 stack and queue (simple)

2022-06-25 12:59:00 Lingtree

The finger of the sword Offer 09. Queues are implemented with two stacks https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

import java.util.Stack;

class CQueue {
    Stack<Integer> a;
    Stack<Integer> b;

    public CQueue() {
        a = new Stack<Integer>();
        b = new Stack<Integer>();
    }

    public void appendTail(int value) {
        a.push(value);
    }

    public int deleteHead() {
        if(b.empty()) {
            while(!a.empty()){
                b.push(a.pop());
            }
        }

        if(b.empty()){
            return -1;
        }
        else{
            return b.pop();
        }
    }
}

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

The finger of the sword Offer 30. contain min Function of the stack icon-default.png?t=L9C2https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/

 

import java.util.Stack;

public class MinStack {
    Stack<Integer> a;
    Stack<Integer> b;
    /** initialize your data structure here. */
    public MinStack() {
        a = new Stack<Integer>();
        b = new Stack<Integer>();
    }
    public void push(int x) {
        a.push(x);
        if(b.empty() || b.peek() >= x) {
            b.push(x);
        }
    }

    public void pop() {
        int t = a.pop();
        if(t == b.peek()) {
            int k = b.pop();
        }
    }

    public int top() {
        return a.peek();
    }

    public int min() {
        int pos = b.size() - 1;
        return b.peek();
    }
}

原网站

版权声明
本文为[Lingtree]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251219269619.html