题目描述
用两个栈来实现一个队列,使用n个元素来完成n次在队列尾部插入整数(push),和n次在队列头部删除整数(pop)的功能。队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
数据范围:n<=1000
要求:存储n个元素的空间复杂度为O(n),插入与删除的时间复杂度都是O(1)
题目来源
略
示例
输入:
["PSH1","PSH2","POP","POP"]
输出:
1,2
说明:
"PSH1":代表将1插入队列尾部
"PSH2":代表将2插入队列尾部
"POP":代表删除一个元素,先进先出=>返回1
"POP":代表删除一个元素,先进先出=>返回2
思路
两个栈联合操作,PUSH操作只在栈1进行,POP操作只在栈2进行,进行PUSH操作前将数据都放入栈1之中,POP操作前将数据都放入栈2中。
具体实现
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>//引入sort()函数
#include <cstring>//调用strcmp()函数
using namespace std;
int main()
{
string str;
string temp;
int num= 0;
int len = 0;
int tempval;
stack<int> push_s,pop_s;
vector<string> inputstr;
cout << "input: " << endl;
cin>>str;
for(int i =0;i<str.length();i++)
{
if(str[i]==' ')
{
continue;
}
if(str[i]=='"')
{
continue;
}
if(str[i]=='[')
{
continue;
}
if(str[i]==','||str[i]==']')
{
if(!strcmp((temp.substr(0,3)).c_str(),"PSH"))
{
temp = temp.erase(0,3);
//cout<<"push temp="<<temp<<endl;
tempval = atoi(temp.c_str());
//cout<<"tempval="<<tempval<<endl;
for(int i =0;i<pop_s.size();i++)
{
int j =pop_s.top();
//cout<<"j="<<j;
push_s.push(j);
pop_s.pop();
}
push_s.push(tempval);
//cout<<"push tempva;="<<temp<<endl;
}
else if(!strcmp(temp.substr(0,3).c_str(),"POP"))
{
for(int i =0;i<push_s.size();i++)
{
int j = push_s.top();
pop_s.push(j);
push_s.pop();
}
cout<<pop_s.top()<<",";
pop_s.pop();
}
temp="";
continue;
}
temp += str[i];
}
cout<<"\b "<<endl;
return 0;
}
时间复杂度
O(n^2)
小结
输入输出处理还有较大改进空间。应当尝试自己编写栈代码。