leetcode232: 用棧實現隊列



一、題目

網址用棧實現隊列

使用棧實現隊列的下列操作:

  • push(x) – 將一個元素放入隊列的尾部。
  • pop() – 從隊列首部移除元素。
  • peek() – 返回隊列首部的元素。
  • empty() – 返回隊列是否爲空。

示例:

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, size, 和 is empty 操作是合法的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。

二、程序

思路:利用一個輔助棧實現隊列。

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack<int> temp;
        while(!data.empty())
        {
            temp.push(data.top());
            data.pop();
        }
        temp.push(x);
        while(!temp.empty())
        {
            data.push(temp.top());
            temp.pop();
        }
        
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int x=data.top();
        data.pop();
        return x;  
    }
    
    /** Get the front element. */
    int peek() {
        return data.top();
        
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return data.empty();
        
    }

private:
    stack<int> data;
};

/**
 * 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();
 */

結果:
在這裏插入圖片描述

發佈了90 篇原創文章 · 獲贊 37 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章