错误栈

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<iostream.h>

#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define INFEASIBLE -1
typedef int SElemType;
typedef int Status;

typedef struct
{
	SElemType *base;
	SElemType *top;
	int stacksize;
}SqStack; 

//顺序栈的初始化
Status InitStack(SqStack &S)
{
	S.base=new SElemType[MAXSIZE];
	if(!S.base) exit(OVERFLOW);
	S.top=S.base;
	S.stacksize=MAXSIZE;
	return OK;
}

//入栈
Status Push(SqStack &S,SElemType e)
{
	if(S.top-S.base==S.stacksize) return ERROR;
	*S.top++=e;
	return OK;
}

//出栈
Status Pop(SqStack &S,SElemType &e)
{
	if(S.top==S.base) return ERROR;
	e=*--S.top;
	return OK;
}

//取栈顶元素

SElemType GetTop(SqStack S)
{
	if(S.top!=S.base)
		return *(S.top-1);
}



//P78页 表3.1
char Precede(char a1,char a2)
{
	char r;
	switch(a2)
	{
	case'+':
	case'-':
		if(a1=='(' || a1=='#')
			r='<';
		else
			r='>';
		break;
	case'*':
	case'/':
		if(a1=='*' || a1=='/' || a1==')')
			r='>';
		else
			r='<';
		break;
	case '(':
		if(a1 == ')')
		{
			cout<<"括号匹配错误"<<endl;
			exit(-1);
		}
		else
			r = '<';
		break;
	case ')':
		if(a1 == '(')
			r = '=';
		else if(a1 == '#')
		{
			cout<<"error,没有左括号"<<endl;
		}
		else
			r = '>';
		break;
	case '#':
		switch(a1)
		{
		case'#':
			r='=';
			break;
		case'(':
			cout<<"error!没有右括号"<<endl;
			exit(-1);
		default:
			r='>';
		}//switch
		break; 
	}
	return r;
}

//判断是否为操作符
char In(char d)
{
	switch(d)
	{
	case '+':
	case '-':
	case '*':
	case '/':
	case '(':
	case ')':
	case '#':
		return true;
	default:
		return false;
	}
}

//运算函数
int Operate(int a, int Opera, int b)
{
	char n = (char)Opera;
	switch(n)
	{
	case '+':
		return a+b;
	case '-':
		return a-b;
	case '*':
		return a*b;
	case '/':
		if(b!=0)
			return a/b;
		else
		{
			cout<<"除数不能为0"<<endl;
			exit(-1);
		} 
	}
}
//
char EvaluateExpression()
{
	SqStack OPTR;
	SqStack OPND;
	char ch;
	int theta,a,b,x;
	InitStack(OPND);
	InitStack(OPTR);
	Push(OPTR,'#');
	cin>>ch;
	
	while(ch!='#' || GetTop(OPTR)!='#')
	{
		if(!In(ch)) {Push(OPND,ch);cin>>ch;}
		else
			switch(Precede(GetTop(OPTR),ch))
		{
			case'<':
				Push(OPTR,ch); cin>>ch;
				break;
			case'>':
				Pop(OPTR,theta);
				Pop(OPND,b);Pop(OPND,a);
				Push(OPND,Operate(a,theta,b));
				break;
			case'=':
				Pop(OPTR,x);cin>>ch;
				break;
		}
		
	}
	return GetTop(OPND);
}

int main()
{
	int Result;
	cout<<"Please Input Num with # to end"<<endl;
	Result = EvaluateExpression();
	cout<<"The result="<<Result<<endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值