《劍指Offer》Java語言-用兩個棧實現佇列
阿新 • • 發佈:2019-02-06
題目描述
用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
思路
這個題目有幾種思路。第一種,把第二個棧作為輔助空間。當push操作時,壓入到第一個棧中。當要pop操作的時候,將元素從第一個棧中彈出到第二個棧中,然後出棧一個元素。然後再將元素入棧到第一個棧中。時間效率為O(N^2)第二種思路:兩個棧互相作為輔助空間。入棧操作到第一個棧中,然後出棧的時候,如果第二個為空,則把第一個棧的元素出棧到第二個棧中。如果是push操作,將第二個棧的元素放到第一個中,然後再入棧。這樣平均複雜度為O(N)
程式碼
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if (stack2.empty()) {
stack1.push(node);
} else {
int size = stack2.size();
for (int i =0; i<size;i++) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
}
public int pop() {
int result = 0;
if (stack2.empty()) {
if (stack1.empty()) {
return 0;
} else {
int size = stack1.size();
for (int i = 0; i <size; i++) {
stack2.push(stack1.pop());
}
result = stack2.pop();
}
} else {
result = stack2.pop();
}
return result;
}
}