232. 用棧實現佇列
阿新 • • 發佈:2021-12-08
請你僅使用兩個棧實現先入先出佇列。佇列應當支援一般佇列支援的所有操作(push、pop、peek、empty):
實現 MyQueue 類:
void push(int x) 將元素 x 推到佇列的末尾
int pop() 從佇列的開頭移除並返回元素
int peek() 返回佇列開頭的元素
boolean empty() 如果佇列為空,返回 true ;否則,返回 false
說明:
你只能使用標準的棧操作 —— 也就是隻有push to top,peek/pop from top,size, 和is empty操作是合法的。
你所使用的語言也許不支援棧。你可以使用 list 或者 deque(雙端佇列)來模擬一個棧,只要是標準的棧操作即可。
進階:
你能否實現每個操作均攤時間複雜度為 O(1) 的佇列?換句話說,執行 n 個操作的總時間複雜度為 O(n) ,即使其中一個操作可能花費較長時間。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.Stack; class MyQueue { private Stack<Integer> stack1; private Stack<Integer> stack2; public MyQueue() { this.stack1 = new Stack<>(); this.stack2 = new Stack<>(); } public void push(int x) { stack1.push(x); } public int pop() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } public int peek() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } return stack2.peek(); } public boolean empty() { return stack1.isEmpty() && stack2.isEmpty(); } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */