您的位置:首页 > 其它

【5】用两个栈实现队列

2016-06-22 11:07 766 查看

【5】用两个栈实现队列

时间限制:1秒

空间限制:32768K

本题知识点: 栈 队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

题目链接:牛客网题目

vs2010编译通过

完整代码:

#include<iostream>
#include<stack>
using namespace std;

class Solution
{
public:
void push(int node) {
while(!stack2.empty())
{
stack1.push( stack2.top() );
stack2.pop();
}
stack1.push(node);
}

int pop() {
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
int temp=stack2.top();
stack2.pop();
return temp;
}

bool empty() //如何判断栈空和栈满。
{
if(stack1.empty() && stack2.empty())
return true;
else
return false;
}
private:
stack<int> stack1;
stack<int> stack2;
};

int main()
{
Solution qs;
qs.push(1);
qs.push(2);
qs.push(3);
cout<<qs.pop()<<endl;
qs.push(4);
while(!qs.empty())
{
cout<<qs.pop()<<endl;
}
//cout<<qs.pop();
//cout<<qs.pop();
}


方法一:

算法部分:不停倒换,复杂度较高

class Solution
{
public:
void push(int node) {
while(!stack2.empty())
{
stack1.push( stack2.top() );
stack2.pop();
}
stack1.push(node);
}

int pop() {
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
int temp=stack2.top();
stack2.pop();
return temp;
}

private:
stack<int> stack1;
stack<int> stack2;
};


方法二:

算法部分,有点像流的缓冲区的感觉,避免不停倒换,时间效率更高

class Solution
{
public:
void push(int node) {
stack1.push(node);
}

int pop() {
if(stack2.empty()) //如果栈2为空,将栈1中的元素流过来
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int result=stack2.top();
stack2.pop();
return result;
}
private:
stack<int> stack1; //只负责入栈
stack<int> stack2; //只负责出
};


测试通过图片

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  visual studio 2010