面试算法-119-用栈实现队列

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾

int pop() 从队列的开头移除并返回元素

int peek() 返回队列开头的元素

boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

你 只能 使用标准的栈操作 ------ 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例 1:

输入:

"MyQueue", "push", "push", "peek", "pop", "empty"

\[\], \[1\], \[2\], \[\], \[\], \[\]

输出:

null, null, null, 1, 1, false

解释:

MyQueue myQueue = new MyQueue();

myQueue.push(1); // queue is: [1]

myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)

myQueue.peek(); // return 1

myQueue.pop(); // return 1, queue is [2]

myQueue.empty(); // return false

java 复制代码
class MyQueue {
    LinkedList<Integer> stack1;
    LinkedList<Integer> stack2;

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

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

    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public int peek() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }

        return stack2.peek();
    }

    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }
}
相关推荐
apocelipes4 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
Full Stack Developme5 小时前
java.text 包详解
java·开发语言·python
刘梦凡呀6 小时前
C#获取钉钉平台考勤记录
java·c#·钉钉
丁浩6666 小时前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
best_virtuoso6 小时前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
yudiandian20146 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
伏小白白白7 小时前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
楚韵天工7 小时前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
helloworddm7 小时前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
失散137 小时前
分布式专题——43 ElasticSearch概述
java·分布式·elasticsearch·架构