一.解法
https://leetcode-cn.com/problems/implement-queue-using-stacks/
要点:辅助栈
Python,C++,Java都用了双栈法,a栈负责进,b栈负责出,需要取首位或者pop首位时,b如果非空直接取b首位,否则将a中元素逆着全部加进b栈。
二.Python实现
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.instack = []
self.outstack = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.instack.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if len(self.outstack) == 0:
while self.instack:
self.outstack.append(self.instack.pop())
return self.outstack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if len(self.outstack) == 0:
while self.instack:
self.outstack.append(self.instack.pop())
return self.outstack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return len(self.instack) == 0 and len(self.outstack) == 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()
三.C++实现
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
stack<int> a;
stack<int> b;
/** Push element x to the back of queue. */
void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int temp;
if(b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
temp=b.top();
b.pop();
}
else {temp=b.top();b.pop();}
return temp;
}
/** Get the front element. */
int peek() { int temp;
if(b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
temp=b.top();}
else {temp=b.top();}
return temp;
}
/** Returns whether the queue is empty. */
bool empty() {
return a.empty()&&b.empty();
}
};
/**
* 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();
* bool param_4 = obj->empty();
*/
四.java实现
class MyQueue {
private Stack<Integer> a;// 输入栈
private Stack<Integer> b;// 输出栈
/** Initialize your data structure here. */
public MyQueue() {
a = new Stack<>();
b = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
/** Get the front element. */
public int peek() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return a.isEmpty() && b.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();
*/