LeetCode 225:用佇列實現棧 Implement Stack using Queues
阿新 • • 發佈:2019-12-31
題目:
使用佇列實現棧的下列操作:
- push(x) -- 元素 x 入棧
- pop() -- 移除棧頂元素
- top() -- 獲取棧頂元素
- empty() -- 返回棧是否為空
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.
示例:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // 返回 2
stack.pop(); // 返回 2
stack.empty(); // 返回 false
複製程式碼
注意:
- 你只能使用佇列的基本操作-- 也就是
push to back
,peek/pop from front
,size
,和is empty
這些操作是合法的。 - 你所使用的語言也許不支援佇列。 你可以使用 list 或者 deque(雙端佇列)來模擬一個佇列,只要是標準的佇列操作即可。
- 你可以假設所有操作都是有效的(例如,對一個空的棧不會呼叫 pop 或者 top 操作)
Notes:
- You must use only standard operations of a queue -- which means only
push to back
,andis 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).
解題思路:
方法一(兩個佇列):
佇列先進後出,棧後進先出。用佇列實現棧,可以用兩個佇列完成題解:
出入棧:
入棧時用 queue1 來存入節點;出棧時queue1 內節點順序出佇列併入佇列到 queue2,直到queue1剩最後一個元素時即為棧頂元素,彈出即可;
取棧頂元素:
用一個 top 指標一直指向棧頂元素,top() 方法查詢棧頂元素時直接返回 top 指標即可。
方法二(一個佇列):
只用一個佇列,只需要在入棧時反轉佇列即可:
入棧存入到佇列queue
節點1入棧:queue:1
反轉佇列0次:queue:1
節點2入棧queue:1->2
反轉佇列1次:
queue:1->2 --> queue:2->1
節點2入棧queue:2->1->3
反轉佇列2次:
queue:2->1->3 ---> queue:1->3->2 ---> queue:3->2->1
......
複製程式碼
這樣不管什麼時候出隊順序都是按照出棧的順序。
Java:
方法一
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
private int top;//指向棧頂元素
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
top = x;//新加入元素為棧頂元素
}
public int pop() {
while (queue1.size() > 1) {//條件為佇列1的元素個數大於一
top = queue1.poll();//用top暫存元素,當迴圈結束時,top剛好是棧頂元素
queue2.add(top);
}
//佇列1與佇列2交換
Queue<Integer> tmp = queue2;
queue2 = queue1;
queue1 = tmp;
return queue2.poll();//返回佇列2的佇列頭元素,佇列2也只有一個元素
}
public int top() {
return top;
}
public boolean empty() {
return queue1.isEmpty();//佇列1決定了棧是否為空
}
}
複製程式碼
方法二:
每次入隊時反轉佇列即可,只有入棧需要特殊操作,出棧、取棧頂元素、是否空都按照佇列正常出佇列、取佇列頭元素、是否空方法操作。下面是入棧時程式碼:
Queue<Integer> queue = new LinkedList<>();
public void push(int x) {
queue.add(x);
int sz = queue.size();//獲得佇列長度
while (sz > 1) {//反轉次數為佇列長度減一
queue.add(queue.remove());//反轉
sz--;
}
}
複製程式碼
Python:
Python語言沒有棧和佇列資料結構,只能用陣列 List 或雙端佇列 deque 實現。
這類程式語言就壓根不需要 用佇列實現棧或用棧實現佇列這種問題,因為棧和佇列本身就必須藉助List、deque實現。
所以這道題在這種語言中這就非常簡單了,可以說是作弊。
class MyStack:
def __init__(self):
self.stack = []
def push(self,x: int) -> None:
self.stack.append(x)
def pop(self) -> int:
return self.stack.pop(-1)
def top(self) -> int:
return self.stack[-1]
def empty(self) -> bool:
return not self.stack
複製程式碼
歡迎關注微.信公.眾號:愛寫Bug