題目描述:
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
解題思路:
本題的基本意圖是:用兩個后入先出的棧來實現先入先出的隊列。對於這個問題,我們可以通過一個實例來進行具體分析。不難得出相應的規律:有兩個棧stack1和stack2,每次向隊列中插入元素可以都壓入到stack1中,當需要從隊列中刪除元素時,我們應該是刪除最早插入的那個(FIFO),這時可以將stack1中的元素逐個彈出並壓入stack2,直到stack1為空,這時最早插入的元素就位於stack2的棧頂,可以直接彈出。
因此,我們總結如下:壓入元素時,都壓入棧1,當需要彈出時,從棧2彈出,當棧2不為空時直接彈出棧頂元素,為空時將棧1的元素“倒進去”。
舉例:

編程實現(Java):
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.empty()){ //為空時將棧1的元素“倒進去”
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
擴展:用兩個隊列實現一個棧
用兩個隊列實現棧相比稍微復雜,當插入一個元素時,可以選擇不為空的那個隊列直接加進去,而當刪除一個元素時,需要借助另一個空隊列,首先依次刪除原隊列的頭,並將刪除的元素加入另一個隊列,直到找到隊列最后一個元素,將其刪除,這時原來的數據隊列變空,另一個隊列變為數據棧。

class MyStack {
Queue<Integer> q1,q2;
int topValue;
/** Initialize your data structure here. */
public MyStack() {
q1=new LinkedList<>();
q2=new LinkedList<>();
topValue=0;
}
/** Push element x onto stack. */
public void push(int x) { //壓入到不為空的那個隊列中
if(!q1.isEmpty())
q1.add(x);
else
q2.add(x);
topValue=x;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int temp=0;
while(!q1.isEmpty()){ //q1不空
temp=q1.poll();
if(q1.isEmpty())
return temp;
q2.add(temp);
topValue=temp;
}
while(!q2.isEmpty()){ //q1不空
temp=q2.poll();
if(!q2.isEmpty()){
q1.add(temp);
topValue=temp;
}
}
return temp;
}
/** Get the top element. */
public int top() {
return topValue;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}