今天继续刷LeetCode,第232题,用栈实现队列的操作。
分析:
在C++中,可以通过两个栈来实现队列的操作,因为队列是先进先出,那么对于一个先进后出的栈来说,从一个栈到另一个栈,就实现了数据的反转,那么就可以实现先进先出了。
对Python中,可以通过列表的方式,存储队列,因为每次存储可以选择放在第一位,或者最后一位,那么对于先进先出的特性来说,就可以选择放在列表第一位,那么出队列就是输出最后一位,很方便。
问题:
1、栈与列表的转换在C++是两个栈来实现
2、在Python中,可以利用append函数和insert函数实现。
附上C++代码:
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
stack<int> temp;
while(s.size()!=1)
{
temp.push(s.top());
s.pop();
}
int value=s.top();
s.pop();
while(temp.size()!=0)
{
s.push(temp.top());
temp.pop();
}
return value;
}
/** Get the front element. */
int peek() {
stack<int> temp;
while(s.size()!=1)
{
temp.push(s.top());
s.pop();
}
int value=s.top();
while(temp.size()!=0)
{
s.push(temp.top());
temp.pop();
}
return value;
}
/** Returns whether the queue is empty. */
bool empty() {
return s.empty();
}
private:
stack<int> s;
int peak_value;
};
/**
* 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();
*/
附上Python代码:
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.inStack=[]
self.outStack=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.inStack.append(x);
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
value=self.inStack[0]
for _ in range(1,len(self.inStack)):
self.outStack.insert(0,self.inStack.pop())
self.inStack=self.outStack
self.outStack=[]
return value
def peek(self) -> int:
"""
Get the front element.
"""
return self.inStack[0]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not len(self.inStack)
# 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()
附上代码Python代码2:
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack.insert(0,x);
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
return self.stack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
return self.stack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not len(self.stack)
# 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()