面试算法-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();
    }
}
相关推荐
To_OC18 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
阿维的博客日记20 小时前
MultipartFile 是不是表示仅仅是一个分片?
java·后端·spring·multipartfile
renhongxia120 小时前
世界模型,是“空中楼阁”还是AGI的“最后一块拼图”?
运维·服务器·数据库·人工智能·算法·agi
程序员无隅20 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+9920 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子20 小时前
浅记java线程池
java·开发语言
一路向北North20 小时前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
zephyr051 天前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米1 天前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
爱吃牛肉的大老虎1 天前
rust基础之环境搭建
java·开发语言·rust