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();
 */
  • 时间复杂度:无。
  • 空间复杂度:无。
相关推荐
xphjj1 小时前
树形数据模糊搜索
前端·javascript·算法
宝桥南山1 小时前
DeepSeek - 尝试一下GitHub Models中的DeepSeek
microsoft·ai·微软·c#·github·.net
Once_day1 小时前
代码训练LeetCode(24)数组乘积
算法·leetcode
独行soc2 小时前
2025年渗透测试面试题总结-腾讯[实习]玄武实验室-安全工程师(题目+回答)
linux·安全·web安全·面试·职场和发展·渗透测试·区块链
int型码农3 小时前
数据结构第八章(二)-交换排序
c语言·数据结构·算法·排序算法
YKPG3 小时前
C++学习-入门到精通【14】标准库算法
c++·学习·算法
CoovallyAIHub3 小时前
AI+无人机如何守护濒危物种?YOLOv8实现95%精准识别
深度学习·算法·计算机视觉
码农之王4 小时前
记录一次,利用AI DeepSeek,解决工作中算法和无限级树模型问题
后端·算法
·云扬·4 小时前
【PmHub面试篇】Gateway全局过滤器统计接口调用耗时面试要点解析
面试·职场和发展·gateway
编程绿豆侠6 小时前
力扣HOT100之二分查找: 34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode