用栈实现队列-leetcode

题目描述

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

:先进后出;
队列:先进先出;

思路:
1.使用两个栈stack 、queue ;
2.将数据push到stack中;
3.queue 进行出队,则是stack中出栈,如果queue无数据则stack就行出栈,如果queue 有数据就进行出栈;

 Stack<int> stack = new Stack<int>();
        Stack<int> queue = new Stack<int>();

        public MyQueue()
        {
        }

        public void Push(int x)
        {
            stack.push(x);
        }

        public int Pop()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }                
            }
            int topV = queue.peek();
            queue.pop();
            return topV;
        }

        /** Get the front element. */
        public int Peek()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }
            }
            return queue.peek();
        }

        /** Returns whether the queue is empty. */
        public bool Empty()
        {
            if (queue.isEmpty())
            {
                while (stack.top != null)
                {
                    queue.push(stack.peek());
                    stack.pop();
                }
            }
            if (queue.top == null) return false;
            return true;
        }

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 栈 栈的英文单词是Stack,它代表一种特殊的线性表,这种线性表只能在固定一端(通常认为是线性表的尾端)进行插入,...
    Jack921阅读 5,431评论 0 5
  • 题目地址:https://leetcode-cn.com/problems/implement-queue-usi...
    monkey01阅读 2,839评论 0 0
  • 栈 栈,是先进后出的线性表,标准STL的栈包括如下5种操作,设栈S:1.取出栈顶元素:S.top();2.判断栈是...
    徐凯_xp阅读 3,561评论 0 1
  • 耳机里单曲循环着李子阳深夜版的《如果云知道》,在这个漫漫的深夜,看着窗外的夜空。虽然没有什么云朵,但是我知道...
    鹤乔姑娘阅读 4,262评论 0 3
  • 我上高一的时候,最喜欢学校图书馆的厕所——只有哗哗的冲水声 我常常借口上厕所在里面一待就是半个多小时 我不喜欢在厕...
    绿蒲阅读 1,553评论 0 0

友情链接更多精彩内容