用棧實現隊列-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;
        }

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 棧 棧的英文單詞是Stack,它代表一種特殊的線性表,這種線性表只能在固定一端(通常認為是線性表的尾端)進行插入,...
    Jack921閱讀 1,522評論 0 5
  • 題目地址:https://leetcode-cn.com/problems/implement-queue-usi...
    monkey01閱讀 372評論 0 0
  • 棧 棧,是先進后出的線性表,標準STL的棧包括如下5種操作,設棧S:1.取出棧頂元素:S.top();2.判斷棧是...
    徐凱_xp閱讀 488評論 0 1
  • 耳機里單曲循環著李子陽深夜版的《如果云知道》,在這個漫漫的深夜,看著窗外的夜空。雖然沒有什么云朵,但是我知道...
    鶴喬姑娘閱讀 787評論 0 3
  • 我上高一的時候,最喜歡學校圖書館的廁所——只有嘩嘩的沖水聲 我常常借口上廁所在里面一待就是半個多小時 我不喜歡在廁...
    綠蒲閱讀 207評論 0 0