劍指Offer:面試題7——用兩個棧實現佇列(java實現)
阿新 • • 發佈:2019-01-07
題目描述:用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
首先定義兩個棧
Stack<Integer> stack1 = new Stack<Integer>();//作為進隊的埠
Stack<Integer> stack2 = new Stack<Integer>();//作為出對的埠
思路:兩個棧,有兩個埠,那麼肯定一個是用來入隊的,另一個用來出隊的。同時,由於棧是先進後出的,那麼經過兩次的入棧則會變為先進先出,即,第一次先進後出,第二次後進先出,兩個加起來就變成了先進先出。
故,入隊時,
為了保證隊中的元素在當前元素之前,我們先從s2出棧,進入s1.
具體看程式碼:很簡單
public void push(int node) {
//檢查是否滿了?
//將s2中的元素出棧,進棧到s1中
while(!stack2.isEmpty()){
int x = stack2.pop();
stack1.push(x);
}
//node元素進棧
stack1.push(node);
//stack1中全體元素出棧,進入stack2中
while(!stack1.isEmpty()){
int x = stack1.pop();
stack2.push(x);
}
}
public int pop() {
if(!stack2.isEmpty()){
int x = stack2.pop();
return x;
}else{
return -1;
}
}
當然這是從進隊入手,出隊簡化。反之,我們也可以簡化入隊而讓出隊時考慮到應有情況。程式碼如下:
public void push(int node) {
stack1.push(node);
}
public int pop() {
//檢查s2是否為空
if(stack2.isEmpty()){
//從stack1彈出元素並壓入stack2
while(!stack1.isEmpty()){
int x = stack1.pop();
stack2.push(x);
}
}
//出隊
int head = stack2.pop();
return head;
}
相比之下,第二個方法更簡單一些。