用兩個堆疊實現一個佇列
阿新 • • 發佈:2019-04-15
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中即可
stack1.push(node);
}
//出對列的實現方法
public int pop() {
//判斷stack1是否為空,不為空,則stack1出棧,放到stack2中
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
//stack2的棧尾正好是stack1的棧底,取得佇列的頭一個元素
int first = stack2.pop();
//為啥要做這個操作呢,因為如果再有元素進佇列,如果不把元素移回去,有元素進入,就不是佇列
//好比做事情,看到成功,還有善後工作
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return first;