溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Lintcode40 Implement Queue by Two Stacks solution 題解

發布時間:2020-07-03 11:03:00 來源:網絡 閱讀:509 作者:abcdd1234567890 欄目:開發技術

【題目描述】

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/


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女