代码随想录算法训练营第10天|栈与队列part01

栈实现队列

题目链接

https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html

思路

两个栈,一个入栈,一个出栈

    class MyQueue {

Stack<Integer> stackIn;
Stack<Integer> stackOut;

public MyQueue() {
    stackIn = new Stack();
    stackOut = new Stack();
}

public void push(int x) {
    stackIn.push(x);
}

public int pop() {
    xx();
    return stackOut.pop();
}

public int peek() {
    xx();
    return stackOut.peek();
}

public boolean empty() {
    return stackIn.isEmpty() && stackOut.isEmpty();
}

private void xx() {
    if(stackOut.isEmpty()) {
        while(!stackIn.isEmpty()) {
            stackOut.push(stackIn.pop());
        }
    }
}
}

队列实现栈

题目链接

https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html

思路

    class MyStack {

private Queue<Integer> queue;

public MyStack() {
    queue = new LinkedList();
}

public void push(int x) {
    queue.add(x);
}

public int pop() {
    xx();
    return queue.poll();
}

public int top() {
    xx();
    int a = queue.poll();
    queue.add(a);
    return a;
}

private void xx() {
    int size = queue.size();
    size--;
    while(size > 0){
        queue.add(queue.poll());
        size--;
    }
}

public boolean empty() {
    return queue.isEmpty();
}
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容