LeetCode 面试题 03.04. 化栈为队

文章目录

一、题目

实现一个MyQueue类,该类用两个栈来实现一个队列。

点击此处跳转题目

示例:

MyQueue queue = new MyQueue();

queue.push(1);

queue.push(2);

queue.peek(); // 返回 1

queue.pop(); // 返回 1

queue.empty(); // 返回 false

说明:

  • 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, sizeis empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

二、C# 题解

很简单的题目,进队列时将元素压入 inStack 中,出队列时将 inStack 元素顺序压入 outStack 后弹出顶端元素即可。

csharp 复制代码
public class MyQueue {
    private Stack<int> inStack, outStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        inStack = new Stack<int>();
        outStack = new Stack<int>();
    }
    
    /** Push element x to the back of queue. */
    public void Push(int x) {
        Reverse(outStack, inStack);
        inStack.Push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int Pop() {
        Reverse(inStack, outStack);
        return outStack.Pop();
    }
    
    /** Get the front element. */
    public int Peek() {
        Reverse(inStack, outStack);
        return outStack.Peek();
    }
    
    /** Returns whether the queue is empty. */
    public bool Empty() {
        return (inStack.Count | outStack.Count) == 0;
    }

    // 将 st1 中的元素压入 st2 中
    private void Reverse(Stack<int> st1, Stack<int> st2) {
        while (st1.Count != 0) st2.Push(st1.Pop());
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.Push(x);
 * int param_2 = obj.Pop();
 * int param_3 = obj.Peek();
 * bool param_4 = obj.Empty();
 */
  • 时间复杂度:无。
  • 空间复杂度:无。
相关推荐
想带你从多云到转晴7 小时前
优选算法---双指针
java·算法
Wilber的技术分享7 小时前
【大模型面试八股 2】Function Call、MCP、Skill的区别
人工智能·面试·职场和发展·大模型·llm·agent·智能体开发
小O的算法实验室7 小时前
2026年IEEE TSMC,基于Q学习平衡全局与局部搜索的防空资源分配问题进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谙弆悕博士7 小时前
快速学C语言——第17章:多文件编程与头文件规范
c语言·开发语言·算法·学习方法·头文件·多文件编程
水蓝烟雨8 小时前
2359. 找到离给定两个节点最近的节点
算法·leetcode
澈2078 小时前
哈希表:O(1)查找的终极指南
算法·哈希算法·散列表
雪豹阿伟8 小时前
4.C# —— 循环语句、break、continue
c#·上位机
幻奏岚音8 小时前
AI模型用户画像分析_new
人工智能·算法·计算机视觉·数据挖掘
阿Y加油吧8 小时前
二刷动态规划经典题:从打家劫舍到完全平方数,Java 实现复盘与优化
leetcode
两千次8 小时前
webpost
c#