數組模擬棧求逆波蘭表達式&&字符串string轉int

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
string s[300];
int st[300];
int top;
int pop()
{
	top--;
	return st[top+1];
}
void push(int num)
{
	top++;
	st[top]=num;
}
int main()
{
	int t=1;
	int a=0,b=0,sum=0;
	string temp;	
	while(cin>>s[t])
		t++;
	for(int i=1;i<t;i++)
	{
		temp=s[i];
		if(temp=="+")
		{
			a=pop();
			b=pop();
			push(a+b);
		}
		else if(temp=="-")
		{
			a=pop();
			b=pop();
			push(b-a);
		}
		else if(temp=="*")
		{
			a=pop();
			b=pop();
			push(a*b);
		}
		else if(temp=="/")
		{
			a=pop();
			b=pop();
			push(b/a);
		}
		else
		{
			int temp1=atoi(temp.c_str());
			push(temp1);
		}
	}
	cout<<st[top];
	return 0;
}

樣例輸入

1 2 + 5 4 + ×

樣例輸出

27
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章