思路
設(shè)兩個棧分別為stack1和stack2,入隊(duì)時,就把元素加入到stack1里面,當(dāng)出隊(duì)時,就把stack1里面的元素全部放到stack2里面,最后彈出stack1里面的元素,即為對首元素,注意這個時候stack2里面的元素的順序是入隊(duì)的元素,如果需要繼續(xù)執(zhí)行出隊(duì)操作,直接彈出stack2棧頂?shù)脑丶纯伞?/p>
Paste_Image.png
public class solution{
Stack<Integer> stack1=new Stack();
Stack<Integer> stack2=new Stack();
public void push(int node){
stack1.push(node);
}
public int pop(){
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}