225. 用佇列實現棧
阿新 • • 發佈:2020-07-23
使用佇列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:
你只能使用佇列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
你所使用的語言也許不支援佇列。 你可以使用 list 或者 deque(雙端佇列)來模擬一個佇列 , 只要是標準的佇列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會呼叫 pop 或者 top 操作)。
解題思路:
佇列只能一段插入一段刪除,也就是先進先出原則,那麼要找到棧頂元素,也就是佇列裡最後一個元素,所以就需要另一個佇列作為輔助。
class MyStack { private Queue<Integer> queueOne; private Queue<Integer> queueTwo; private int top; /** Initialize your data structure here. */ public MyStack() { queueOne = new LinkedList<>(); queueTwo = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { queueOne.offer(x); top = x; } /** Removes the element on top of the stack and returns that element. */ public int pop() { while(queueOne.size() > 1) { top = queueOne.poll(); queueTwo.offer(top); } int res = queueOne.poll(); Queue temp = queueTwo; queueTwo = queueOne; queueOne = temp; return res; } /** Get the top element. */ public int top() { return top; } /** Returns whether the stack is empty. */ public boolean empty() { return queueOne.isEmpty(); } }
來源:力扣(LeetCode) 連結:https://leetcode-cn.com/problems/implement-stack-using-queues 著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。