LeetCode 225: Implement Stack using Queues

來源:互聯網
上載者:User

Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty. Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

用兩個隊列類比一個堆棧:

隊列a和b

(1)取棧頂元素: 返回有元素的隊列的首元素

(2)判棧空:若隊列a和b均為空白則棧空

(3)入棧:a隊列當前有元素,b為空白(倒過來也一樣)則將需要入棧的元素先放b中,然後將a中的元素依次出列併入列倒b中。(保證有一個隊列是空的)

(4)出棧:將有元素的隊列出列即可。

比如先將1插入隊a中 ,現在要將2入棧,則將2插入b總然後將a中的1出列入到b中,b中的元素變為 2 ,1

a為空白,現在要壓入3 則將3插入a中 ,依次將b中的2 ,1 出列並加入倒a中 ,a中的元素變為 3,2,1 b為空白

演算法保證在任何時候都有一隊列為空白 代碼如下:

class Stack {public:// Push element x onto stack.queue<int> queue1;queue<int> queue2;void push(int x) {if (queue1.empty()){queue1.push(x);while(!queue2.empty()){int tmp = queue2.front();queue2.pop();queue1.push(tmp);}}else{queue2.push(x);while(!queue1.empty()){int tmp = queue1.front();queue1.pop();queue2.push(tmp);}}}// Removes the element on top of the stack.void pop() {if (!queue1.empty())queue1.pop();if (!queue2.empty())queue2.pop();}// Get the top element.int top() {if (!queue1.empty())return queue1.front();if (!queue2.empty())return queue2.front();}// Return whether the stack is empty.bool empty() {return queue1.empty() && queue2.empty();}};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.