Java教程

P1449 后缀表达式 栈的应用

本文主要是介绍P1449 后缀表达式 栈的应用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

栈的应用
当读到的数时入栈,当读到运算符时,对应数据出栈,计算后再入栈,当读到@时,栈顶为本题的解,这里的栈用C++stl的stack容器,简化代码的实现。

//P1449 后缀表达式
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
typedef long long LL;
stack <LL> sd;
char bds[1001];
int main()
{
	cin>>bds;
	int bdslen=strlen(bds);
	int i=0;
	while (i<bdslen)
	{
		if (bds[i]=='@') break;
		else if (bds[i]=='+')
		{
			int t1,t2;
			t1=sd.top();
			sd.pop();
			t2=sd.top();
			sd.pop();
			sd.push(t1+t2);
			i++;
		}
		else if (bds[i]=='-')
		{
			int t1,t2;
			t1=sd.top();
			sd.pop();
			t2=sd.top();
			sd.pop();
			sd.push(t2-t1);
			i++;
			
		}
		else if (bds[i]=='*')
		{
			int t1,t2;
			t1=sd.top();
			sd.pop();
			t2=sd.top();
			sd.pop();
			sd.push(t1*t2);
			i++;
		}
		else if (bds[i]=='/')
		{
			int t1,t2;
			t1=sd.top();
			sd.pop();
			t2=sd.top();
			sd.pop();
			sd.push(t2/t1);
			i++;
		}
		else
		{
			int t=0;
			while (i<bdslen&&bds[i]>='0'&&bds[i]<='9')
			{
				t=t*10+bds[i]-'0';
				i=i+1;
			}
			sd.push(t);
			i=i+1;
		}
	}
	cout<<sd.top()<<endl;
}

  

这篇关于P1449 后缀表达式 栈的应用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!