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();
 */
  • 时间复杂度:无。
  • 空间复杂度:无。
相关推荐
野生技术架构师1 小时前
金三银四面试总结篇,汇总 Java 面试突击班后的面试小册
java·面试·职场和发展
_深海凉_2 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
ja哇3 小时前
大厂面试高频八股
java·面试·职场和发展
踩坑记录3 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎3 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰3 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx3 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
程序设计实验室3 小时前
Spark.NET:一个试图把 Django / Rails 式开发体验带回 .NET 世界的全栈 Web 框架。
c#
AIFarmer3 小时前
【无标题】
开发语言·c++·算法
AGV算法笔记3 小时前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉