数据结构之堆栈计算器

注:支持+,-,*,/,(,),程序简陋,请确保输入正确的式子,不需要输入等号

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <list> 
#include <map> 
#include <string>
using namespace std; 

#define OK      1   
#define ERROR   0    
#define MAXSIZE 50

int intopost(char *infix,char *postfix)
{
	stack<int>s;
	int i=0,j=0;
	int e=0;
		
	while(infix[i]!='\0')
	{
		while(infix[i]>='0' && infix[i]<='9')
		{
			postfix[j++]=infix[i];
			i++;
			if(infix[i]<'0' || infix[i]>'9')
			postfix[j++]=' ';
		}
		if(infix[i]==')')
		{
			e=s.top();
			s.pop();
			while(e!='(')
			{
				postfix[j++]=e;
				postfix[j++]=' ';
				e=s.top();
				s.pop();				
			}			
		}
		else if(infix[i]=='+' || infix[i]=='-')
		{
			if(s.empty())
			{
				s.push(infix[i]);				
			}
			else 
			{
				do
				{
					e=s.top();
					s.pop();
					if(e=='(')
					s.push(e);
					else
					{
						postfix[j++]=e;
						postfix[j++]=' ';
					}					
				}while(!s.empty() && e!='(');
				s.push(infix[i]);
			}						
		}
		else if(infix[i]=='*' || infix[i]=='/' || infix[i]=='(')
		{
			s.push(infix[i]);
		}
		else if(infix[i]=='\0')
		break;
		else
		return ERROR;
		i++;	
	}
	while(!s.empty())
	{
		e=s.top();
		s.pop();
		postfix[j++]=e;
		postfix[j++]=' ';
	}

	return OK;	
}
int calculate(char *postfix)
{
	stack<int>ss;
	char *op;
	char *buf=postfix;
	int d,e,f;
	int ans=0;
 
	while((op=strtok(buf," "))!=NULL)
	{
		buf=NULL;
		switch(op[0])
		{
			case '+':
				d=ss.top();
				ss.pop();
				e=ss.top();
				ss.pop();
				f=d+e;
				ss.push(f);
				break;
			case '-':
				d=ss.top();
				ss.pop();
				e=ss.top();
				ss.pop();
				f=e-d;
				ss.push(f);
				break;	
			case '*':
				d=ss.top();
				ss.pop();
				e=ss.top();
				ss.pop();
				f=e*d;
				ss.push(f);
				break;
			case '/':
				d=ss.top();
				ss.pop();
				e=ss.top();
				ss.pop();
				f=e/d;
				ss.push(f);
				break;
			default:
				d=atoi(op);
				ss.push(d);
				break;							
		}
	}
	ans=ss.top();
	ss.pop();
	return ans;
}
int main()
{
	char infix[MAXSIZE];
	char postfix[MAXSIZE];
	int ans=0;
	
	cin >>infix;
	
	intopost(infix,postfix);
			
	ans=calculate(postfix);
			
	cout <<ans <<endl;
	
	return 0;
}
//calc::2+(1+(1*1)*(1+(1+1)))


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值