leetcode232:栈实现队列

栈实现队列

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

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false
java 复制代码
class MyQueue {
        Stack<Integer> stack = new Stack<>();

        Stack<Integer> tmp = new Stack<>();

        public MyQueue() {

        }

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

        public int pop() {
            tmp.empty();
            while(!stack.empty()){
                tmp.push(stack.peek());
                stack.pop();
            }
            Integer res = tmp.pop();
            while(!tmp.empty()){
                stack.push(tmp.peek());
                tmp.pop();
            }
            return res;
        }

        public int peek() {
            tmp.empty();
            while(!stack.empty()){
                tmp.push(stack.peek());
                stack.pop();
            }
            Integer res = tmp.peek();
            while(!tmp.empty()){
                stack.push(tmp.peek());
                tmp.pop();
            }
            return res;
        }

        public boolean empty() {
            return stack.empty();
        }
    }

用另一个栈实现

相关推荐
O。O蛋黄酥啊1 分钟前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag
Σίσυφος19005 分钟前
depth_from_focus 详解
算法
圣保罗的大教堂7 分钟前
leetcode 2996. 大于等于顺序前缀和的最小缺失整数 简单
leetcode
疯狂打码的少年15 分钟前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法
树獭哥25 分钟前
量化金融入门:从数据规则到随机游走与凯利公式
人工智能·算法·金融·量化金融
圣保罗的大教堂31 分钟前
leetcode 3702. 按位异或非零的最长子序列 中等
leetcode
薛定e的猫咪1 小时前
(arXiv 2026)GLiBRL :可学习基函数的深度贝叶斯元强化学习 ----待补充
人工智能·深度学习·学习·算法·机器学习
hetao17338371 小时前
2026-08-21~23 hetao1733837 的刷题记录
c++·算法
青 春 记 忆2 小时前
LeetCode 206. 反转链表|Python 解法详解
python·leetcode·链表