用兩個棧來實現一個隊列,完成隊列的推送和彈出操作。隊列中的元素爲INT類型。
我的想法:首先stack1中專門當作入隊,然後stack2中存放棧1的逆序每次進棧時都要保證stack2中沒有彈出出去的數據先還給棧1,之後進棧,之後再把 進棧的stack1 逆序放入stack2 這樣才能保證stack2中存放的永遠是進棧的數據的逆序代碼如下:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(stack2.size()!=0){
stack1.push(stack2.pop());
}
stack1.push(node);
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}
public int pop() {
return stack2.pop();
}
}