1. 程式人生 > >Lintcode40 Implement Queue by Two Stacks solution 題解

Lintcode40 Implement Queue by Two Stacks solution 題解

lintcode

【題目描述】

As the title described, you should only use two stacks to implement a queue‘s actions.The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.Both pop and top methods should return the value of first element.

正如標題所述,你需要使用兩個棧來實現隊列的一些操作。隊列應支持push(element),pop() 和 top(),其中pop是彈出隊列中的第一個(最前面的)元素。pop和top方法都應該返回第一個元素的值。

【題目鏈接】

http://www.lintcode.com/en/problem/implement-queue-by-two-stacks/

【題目解析】

用兩個Stack來實現一個Queue,可以考慮到push()時,幾乎與Queue中的offer()一樣,都是加在末尾,區別是當Stack pop()時,取出的是最近加入(newest)的元素,而Queue用poll()則是將最老(oldest)的元素取出。使用2個Stack,可以將stack2作為push()時的目標,而另一個stack1用來翻轉順序,只有當peek()或者是poll()時,才需要將元素翻轉存入stack1,再進行讀取。

【參考答案】

http://www.jiuzhang.com/solutions/implement-queue-by-two-stacks/


Lintcode40 Implement Queue by Two Stacks solution 題解