232. Implement Queue using Stacks Easy
1/**
2 * [232] Implement Queue using Stacks
3 *
4 * Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
5 * Implement the MyQueue class:
6 *
7 * void push(int x) Pushes element x to the back of the queue.
8 * int pop() Removes the element from the front of the queue and returns it.
9 * int peek() Returns the element at the front of the queue.
10 * boolean empty() Returns true if the queue is empty, false otherwise.
11 *
12 * Notes:
13 *
14 * You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
15 * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
16 *
17 *
18 * Example 1:
19 *
20 * Input
21 * ["MyQueue", "push", "push", "peek", "pop", "empty"]
22 * [[], [1], [2], [], [], []]
23 * Output
24 * [null, null, null, 1, 1, false]
25 * Explanation
26 * MyQueue myQueue = new MyQueue();
27 * myQueue.push(1); // queue is: [1]
28 * myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
29 * myQueue.peek(); // return 1
30 * myQueue.pop(); // return 1, queue is [2]
31 * myQueue.empty(); // return false
32 *
33 *
34 * Constraints:
35 *
36 * 1 <= x <= 9
37 * At most 100 calls will be made to push, pop, peek, and empty.
38 * All the calls to pop and peek are valid.
39 *
40 *
41 * Follow-up: Can you implement the queue such that each operation is <a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a> O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.
42 *
43 */
44pub struct Solution {}
45
46// problem: https://leetcode.com/problems/implement-queue-using-stacks/
47// discuss: https://leetcode.com/problems/implement-queue-using-stacks/discuss/?currentPage=1&orderBy=most_votes&query=
48
49// submission codes start here
50
51struct MyQueue {
52 false
53 }
54
55
56/**
57 * `&self` means the method takes an immutable reference.
58 * If you need a mutable reference, change it to `&mut self` instead.
59 */
60impl MyQueue {
61
62 fn new() -> Self {
63
64 }
65
66 fn push(&self, x: i32) {
67
68 }
69
70 fn pop(&self) -> i32 {
71
72 }
73
74 fn peek(&self) -> i32 {
75
76 }
77
78 fn empty(&self) -> bool {
79
80 }
81}
82
83/**
84 * Your MyQueue object will be instantiated and called as such:
85 * let obj = MyQueue::new();
86 * obj.push(x);
87 * let ret_2: i32 = obj.pop();
88 * let ret_3: i32 = obj.peek();
89 * let ret_4: bool = obj.empty();
90 */
91
92// submission codes end
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn test_232() {
100 }
101}
102
Back
© 2025 bowen.ge All Rights Reserved.