5、用兩個棧實現佇列
阿新 • • 發佈:2018-11-21
用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
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(stack2.size() > 0){
return stack2.pop();
}else{
while(stack1.size()>0){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}
水題一次過。
通過本題再記一下java棧的API:
java . util . Stack < E > 1.0
•E push ( E item )
將 item 壓人桟並返回 item。
•E pop ()
彈出並返回棧頂的 item。 如果棧為空 , 請不要呼叫這個方法 。
•E peek ()
返回棧頂元素, 但不彈出 。 如果棧為空 , 請不要呼叫這個方法。