本文旨在对于个人知识的梳理以及知识的分享,如果有不足的地方,欢迎大家在评论区指出
题目描述
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
题目链接
题目分析
这道题要求我们只可以使用栈有关的操作来实现队列,一个比较经典的方式就是使用两个栈,举一个例子,例如给定一个操作序列为[push, push, pop, peek, push], [1, 2, null, null, 3]
,两个栈依次为sk1
、sk2
,则两个栈的变化为:
push 1:
sk1: [1] sk2: []
push 2:
sk1: [1, 2] sk2: []
pop:
sk1: [] sk2: [2, 1]
之后pop sk2中的元素=> sk1: [] sk2: [2]
peek:
sk1: [] sk2: [2]
返回sk2的栈顶元素即可
push 3:
sk1: [3] sk2: [2]
由此,思路也就比较清晰了
解题代码
Java
class MyQueue {
private Stack<Integer> sk1;
private Stack<Integer> sk2;
/** Initialize your data structure here. */
public MyQueue() {
sk1 = new Stack<Integer>();
sk2 = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
sk1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(sk2.size()!=0) return sk2.pop();
while(sk1.size()!=0) sk2.push(sk1.pop());
return sk2.pop();
}
/** Get the front element. */
public int peek() {
if(sk2.size()!=0) return sk2.peek();
while(sk1.size()!=0) sk2.push(sk1.pop());
return sk2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return sk1.size()==0 && sk2.size()==0;
}
}
/**
* 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();
*/
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.sk1 = []
self.sk2 = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.sk1.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.sk2:
return self.sk2.pop()
while self.sk1:
self.sk2.append(self.sk1.pop())
return self.sk2.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if self.sk2:
return self.sk2[-1]
while self.sk1:
self.sk2.append(self.sk1.pop())
return self.sk2[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.sk1)==0 and len(self.sk2)==0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()