題目描述
用兩個棧來實現(xiàn)一個隊列像鸡,完成隊列的Push和Pop操作。 隊列中的元素為int類型哈恰。
解題思路
1只估,元素進棧放入棧A
2,元素出棧
- 如果棧B有元素着绷,則直接棧B出棧蛔钙。
- 如果棧A有元素,則將棧A的元素全部出棧蓬戚,并且元素進入棧B,然后棧B出棧夸楣。
代碼實現(xià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) {
stack1.push(node);
}
//彈棧
public int pop() {
if(stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException("stack is all empty!");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}