##用兩個堆疊來實作一個佇列,完成佇列的Push和Pop操作, 佇列中的元素為int型別,
思路
push時直接入堆疊stack1,pop時若stack2為空則stack1出堆疊到stack2后stack2.pop(),否則stack2直接pop,
時間復雜度O(1),
代碼
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.empty()) {
while(!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/90057.html
標籤:其他
上一篇:小波多解析度分析框架
下一篇:耗材銷售尋找防盜版方式
