LeetCode—225 用队列实现栈 Cpp&Python
一、方法与思路
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
大体思路与Leetcode225题大致一样,根据栈和队列的性质进行设计
链接: https://blog.csdn.net/weixin_45680994/article/details/108715547.
二、C++代码
#include <stdio.h>
#include <stack>
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
std::stack<int> temp_stack;
while(!_data.empty()){
temp_stack.push(_data.top());
_data.pop();
}
temp_stack.push(x);
while(!temp_stack.empty()){
_data.push(temp_stack.top());
temp_stack.pop();
}
}
int pop() {
int x = _data.top();
_data.pop();
return x;
}
int peek() {
return _data.top();
}
bool empty() {
return _data.empty();
}
private:
std::stack<int> _data;
};
int main(){
MyQueue Q;
Q.push(1);
Q.push(2);
Q.push(3);
Q.push(4);
printf("%d\n", Q.peek());
Q.pop();
printf("%d\n", Q.peek());
return 0;
}
三、Python代码
class MyQueue(object):
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)