【LeetCode-面試演算法經典-Java實現】【225-Implement Stack using Queues(用隊列實現棧操作)】,-javaqueues
【225-Implement Stack using Queues(用隊列實現棧操作)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】代碼下載【https://github.com/Wang-Jun-Chao】原題
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).
題目大意
使用隊列實現棧操作
push(x) – 元素入棧
pop() – 元素出棧
top() – 取棧頂元素值
empty() – 判斷棧是否為空白
注意:
只能使用隊列的標準操作,先進先出,求隊列元素數,判斷隊列是否為空白
由於程式設計語言原因,有些語言不支撫摩隊列,可以使用鏈表或雙向鏈表代替,但僅能使用標準的隊列操作
你可以假設所有的操作都是合法的,即:當隊列為空白時不會有元素出棧和求棧頂元素的操作
解題思路
用兩個隊列來類比一個棧
代碼實現
演算法實作類別
import java.util.LinkedList;import java.util.List;public class MyStack { // 維持兩個隊列,其中總有一個隊列為空白,為pop和top操作準備 private List<Integer> aList = new LinkedList<>(); private List<Integer> bList = new LinkedList<>(); // Push element x onto stack. public void push(int x) { // 如果aList非空,就將x添加到aList中 if (!aList.isEmpty()) { aList.add(x); } // 否則總添加到bList中 else { bList.add(x); } } // Removes the element on top of the stack. public void pop() { // 兩個隊列中至少有一個為空白,將aList設定非空 if (aList.isEmpty()) { List<Integer> tmp = bList; bList = aList; aList = tmp; } // 除最後一個元素外都轉移到bList中 while (aList.size() > 1) { bList.add(aList.remove(0)); } // 刪除最後一個元素(對應就是入棧的棧頂元素) aList.clear(); } // Get the top element. public int top() { // 兩個隊列中至少有一個為空白,將aList設定非空 if (aList.isEmpty()) { List<Integer> tmp = bList; bList = aList; aList = tmp; } // 除最後一個元素外都轉移到bList中 while (aList.size() > 1) { bList.add(aList.remove(0)); } bList.add(aList.get(0)); return aList.remove(0); } // Return whether the stack is empty. public boolean empty() { return aList.isEmpty() && bList.isEmpty(); }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/48084069】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。