用栈解决后缀表达式的求值

实现如下的显示结果:



#include<iostream>
#include<string>
using namespace std;
#define NUM 20

template <class T>
class Stack
{
private:
	int Size;
	T * top_p;
	int maxSize;
public:
	void create();
	void push(T x);
	int pop();
	int top();
	bool isEmpty();
	void traverse();
};

template<class T>
void Stack<T>::create()
{
	top_p=new T [NUM];
	Size=0;
	maxSize=NUM;
}
template<class T>
void Stack<T>::push(T x)
{
	if(Size<maxSize) {*top_p=x;top_p++;Size++;}
	else cout<<"The Stack is full !";
}
template<class T>
int Stack<T>::pop()
{
	if(Size==0) {cout<<"There is no data !"; return -1;}
	else {Size--;int res=*(top_p-1);top_p--;return res;}
}
template<class T>
int Stack<T>::top()
{
	if(Size==0) {cout<<"There is no data !";return 0;}
	else {return *(top_p-1);}
}

template<class T>
bool Stack<T>::isEmpty()
{
	if(Size==0) return false;
	else return true;
}


template<class T> //template <typename T>
void Stack<T>::traverse()
{
	int i=0;
	T *tmp=top_p;
	if(Size==0) {cout<<"There is no data !";}
	while(i!=Size)
	{   cout<<*(--tmp)<<"  ";
		i++;
	}
}
bool isdigit(char s)
{
	if(s<='9' && s>='0') return true;
	else return false;
}
<span style="font-family: Arial, Helvetica, sans-serif;">int str2int(string str)</span>
{
	int tmp=0;
	int i=0;
	while(i<str.size())
	{
		tmp=tmp*10+str[i]-'0';
		i++;
	}
	return tmp;

}
int Polyn(string l)
{
	Stack<int> s;
	s.create();
	int i=0;
	string tmp="";	
	while(i!=l.size())
	{
		if(l[i]!=' ')
		{ 
		   	if(isdigit(l[i])) {tmp.push_back(l[i]);i++; }
			else
			{
				int lt,rt;
				rt=s.pop();
				lt=s.pop();				
				switch(l[i])
				{
					case '+': s.push(lt+rt);break;
				        case '-': s.push(lt-rt);break;
					case '*': s.push(lt*rt);break;
					case '/': s.push(lt/rt);break;
					
			    }
				i++;
			}
		}
		else 
		{   if(isdigit(l[i-1]))
		{s.push(str2int(tmp));i++;tmp="";}
		else 
			i++;
		}
	}
	return s.top();
}
int main()
{
	string l;
	getline(cin,l,'\n');
	cout<<Polyn(l)<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值