• 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 后弹出顶端元素即可。

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 时间复杂度:无。
    • 空间复杂度:无。
  • 相关阅读:
    leetcode算法每天一题029:两数相除
    【业务架构】价值实现、价值定位、价值创造
    亚马逊频繁封号,跨境电商卖家如何应对?
    【API篇】二、源算子API
    Ansible-常用模块
    Vue中使用Google的reCAPTCHA v3人机校验-demo
    Windows安装Nginx及部署vue前端项目操作
    计算机网络-网络层详细讲解
    Vue源码学习之代码实现生成原理及render函数执行准备
    [Android开发学iOS系列] Auto Layout
  • 原文地址:https://blog.csdn.net/zheliku/article/details/132724669