Day22 用2个栈实现队列

题目描述

用两个栈来实现一个队列,使用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)

小结

输入输出处理还有较大改进空间。应当尝试自己编写栈代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值