# LeetCode225:Implement Stack using Queues

616人阅读 评论(0)

Implement the following operations of a stack using queues.

• push(x) – Push element x onto stack.
• pop() – Removes the element on top of the stack.
• top() – Get the top element.
• empty() – Return whether the stack is empty.

Notes:

• You must use only standard operations of a queue – which means only
push to back, peek/pop from front, size, and is empty operations are
valid.
• Depending on your language, queue may not be supported natively. You
may simulate a queue by using a list or deque (double-ended queue),
as long as you use only standard operations of a queue. You may
assume that all operations are valid (for example, no pop or top
operations will be called on an empty stack).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

Hide Tags Stack Data Structure

C++代码如下：
runtime:0ms

class Stack {
public:
// Push element x onto stack.
void push(int x) {
if(queueOne.empty())
{
queueTwo.push(x);
}else
{
queueOne.push(x);
}
}

// Removes the element on top of the stack.
void pop() {
if(queueOne.empty())
{
while(queueTwo.size()!=1)
{
queueOne.push(queueTwo.front());
queueTwo.pop();
}
queueTwo.pop();
}
else
{
while(queueOne.size()!=1)
{
queueTwo.push(queueOne.front());
queueOne.pop();
}
queueOne.pop();
}
}

// Get the top element.
int top() {
if(queueOne.empty())
{
while(queueTwo.size()!=1)
{
queueOne.push(queueTwo.front());
queueTwo.pop();
}
int result=queueTwo.front();
queueOne.push(queueTwo.front());
queueTwo.pop();
return result;
}
else
{
while(queueOne.size()!=1)
{
queueTwo.push(queueOne.front());
queueOne.pop();
}
int result=queueOne.front();
queueTwo.push(queueOne.front());
queueOne.pop();
return result;
}
}

// Return whether the stack is empty.
bool empty() {
return queueOne.empty()&&queueTwo.empty();
}

private:
queue<int> queueOne;
queue<int> queueTwo;
};

C++代码如下：
runtime:0ms

class Stack {
public:
// Push element x onto stack.
void push(int x) {
q.push(x);
for(int i=0;i<q.size()-1;i++)
{
q.push(q.front());
q.pop();
}
}

// Removes the element on top of the stack.
void pop() {
q.pop();
}

// Get the top element.
int top() {
return q.front();
}

// Return whether the stack is empty.
bool empty() {
return q.empty();
}

private:
queue<int> q;
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：334616次
• 积分：6173
• 等级：
• 排名：第4165名
• 原创：261篇
• 转载：43篇
• 译文：13篇
• 评论：43条
友情链接
博客专栏
 设计模式（C++） 文章：24篇 阅读：16542
 LeetCode 文章：94篇 阅读：66273
 openGL系列教程 文章：13篇 阅读：27794
文章分类
评论排行
最新评论