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();
 */
  • 时间复杂度:无。
  • 空间复杂度:无。
相关推荐
Gyoku Mint1 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
葫三生2 小时前
如何评价《论三生原理》在科技界的地位?
人工智能·算法·机器学习·数学建模·量子计算
Nemo_XP4 小时前
HttpHelper类处理两种HTTP POST请求
c#
拓端研究室5 小时前
视频讲解:门槛效应模型Threshold Effect分析数字金融指数与消费结构数据
前端·算法
随缘而动,随遇而安7 小时前
第八十八篇 大数据中的递归算法:从俄罗斯套娃到分布式计算的奇妙之旅
大数据·数据结构·算法
IT古董7 小时前
【第二章:机器学习与神经网络概述】03.类算法理论与实践-(3)决策树分类器
神经网络·算法·机器学习
Alfred king10 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
水木兰亭10 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
lijingguang10 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
June bug11 小时前
【软考中级·软件评测师】下午题·面向对象测试之架构考点全析:分层、分布式、微内核与事件驱动
经验分享·分布式·职场和发展·架构·学习方法·测试·软考