題目描述
用兩個(gè)棧來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類型。
解題思路
1,元素進(jìn)棧放入棧A
2,元素出棧
- 如果棧B有元素,則直接棧B出棧。
- 如果棧A有元素,則將棧A的元素全部出棧,并且元素進(jìn)入棧B,然后棧B出棧。
代碼實(shí)現(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();
}
}