admin管理员组文章数量:1637205
Implement the following operations of a queue using stacks.
- push(x) – Push element x to the back of queue.
- pop() – Removes the element from in front of queue.
- peek() – Get the front element.
- empty() – Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack – which means only
push to top, peek/pop from top, size, and is empty operations are
valid. - Depending on your language, stack may not be supported natively. You
may simulate a stack by using a list or deque (double-ended queue),
as long as you use only standard operations of a stack. - You may assume that all operations are valid (for example, no pop or
peek operations will be called on an empty queue).
使用栈来实现一个队列,这个题目之前在《剑指offer》上面见过,没有什么好说的。使用两个栈,一个栈用来保存插入的元素,另外一个栈用来执行pop或top操作,每当执行pop或top操作时检查另外一个栈是否为空,如果为空,将第一栈中的元素全部弹出并插入到第二个栈中,再将第二个栈中的元素弹出即可。需要注意的是这道题的编程时有一个技巧,可以使用peek来实现pop,这样可以减少重复代码。编程时要能扩展思维,如果由于pop函数的声明再前面就陷入用pop来实现peek的功能的话就会感觉无从下手了。
runtime:0ms
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
pushStack.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
peek();//这里可以使用peek进行两个栈之间元素的转移从而避免重复代码
popStack.pop();
}
// Get the front element.
int peek(void) {
if(popStack.empty())
{
while(!pushStack.empty())
{
popStack.push(pushStack.top());
pushStack.pop();
}
}
return popStack.top();
}
// Return whether the queue is empty.
bool empty(void) {
return pushStack.empty()&&popStack.empty();
}
private:
stack<int> pushStack;//数据被插入到这个栈中
stack<int> popStack;//数据从这个栈中弹出
};
版权声明:本文标题:LeetCode232:Implement Queue using Stacks 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1729234193a1191803.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论