0232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Example:MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns falseNotes:
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.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
思路
根据题意,使用栈来实现一个队列。先进后出实现先进先出。
这里有提示,如果使用的语言没有实现Stack,就用队列。Python如果使用list来实现队列就非常的简单(算作弊)
这题的基本思路就是使用两个栈,但是具体的操作需要看实现。
可以在入队时变为FIFO,也可以在出队时变为FIFO。
入队如果变FIFO,那么在新进元素的时需要放在栈底,我们只能用另外一个栈暂存元素,放置之后再放回来。
- 时间复杂度 O(N)
- 空间复杂度 O(1)
出队如何变FIFO,那么使用另外一个栈暂存元素,把栈底元素弹出。
- 时间复杂度 O(1) 最坏O(N)
- 空间复杂度 O(1)
代码
struct MyQueue { vec1: Vec<i32>, vec2: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MyQueue { /** Initialize your data structure here. */ fn new() -> Self { MyQueue { vec1: Vec::new(), vec2: Vec::new(), } } /** Push element x to the back of queue. */ fn push(&mut self, x: i32) { while let Some(v) = self.vec1.pop() { self.vec2.push(v); } self.vec2.push(x); while let Some(v) = self.vec2.pop(){ self.vec1.push(v); } } /** Removes the element from in front of queue and returns that element. */ fn pop(&mut self) -> i32 { self.vec1.pop().unwrap() } /** Get the front element. */ fn peek(&self) -> i32 { *self.vec1.last().unwrap() } /** Returns whether the queue is empty. */ fn empty(&self) -> bool { self.vec1.is_empty() } } |
- 执行用时: 0 ms
- 内存消耗: 2.1 MB
题型与相似题
题型
1.栈
2.队列
相似题