Description
Solutions
入隊時,直接向其中一個棧(假設stack1)進行入棧操作;
出隊時,將stack1的除了最裏面的數據,全部依次出棧併入棧stack2,然後stack1剩餘的一個元素就是出隊結果,把它出棧並保存爲臨時變量,用於返回;然後將stack2的數據全部出棧併入棧stack1.
Code
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() {
while(stack1.size() != 1){
stack2.push(stack1.pop());
}
int result = stack1.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return result;
}
}