今天继续刷LeetCode,第225题,用队列的操作来实现栈的功能。
分析:
因为栈是先进后出,那么对于一个先进先出的队列来说,可能无法满足需求,那么就可以通过两个队列来实现一个栈的功能。出栈的时候,选择先出队列,再入队列,将队列最后一个元素输出,就是栈的输出了。
问题:
1、队列用列表的方式表示的时候,可以有两种插入方式,一个是append加入到尾部,一个是insert插入到头部。
2、注意Python中self的应用。
附上C++代码:
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
top_value=x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
queue<int> temp;
while(q.size()!=1)
{
temp.push(q.front());
top_value=q.front();
q.pop();
}
int value=q.front();
q.pop();
q=temp;
return value;
}
/** Get the top element. */
int top() {
return top_value;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
int top_value;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
附上Python代码:
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.inQueue=[]
self.outQueue=[]
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.inQueue.insert(0,x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
for _ in range(len(self.inQueue)-1):
self.outQueue.insert(0,self.inQueue.pop())
res=self.inQueue.pop()
self.inQueue=self.outQueue
self.outQueue=[]
return res
def top(self) -> int:
"""
Get the top element.
"""
for _ in range(len(self.inQueue)-1):
self.outQueue.insert(0,self.inQueue.pop())
res=self.inQueue.pop()
self.outQueue.insert(0,res)
self.inQueue=self.outQueue
self.outQueue=[]
return res
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if len(self.inQueue)==0:
return True
else:
return False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()