数据结构链栈实现简单计算器的操作
未改进,只能计算输出结果是个位数的数值计算
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 100
using namespace std;
typedef char ElemType;
typedef int Status;
typedef struct StackNode{
ElemType data;
struct StackNode *next;
int stacksize;
}StackNode,*LinkStack;
StackNode *p;
LinkStack OPND;
LinkStack OPTR;
Status InitStack (LinkStack &S)
{
S=NULL;
return OK;
}
Status Push(LinkStack &S,ElemType e)
{
p=new StackNode;
p->data=e;
p->next=S;
S=p;
return OK;
}
ElemType Pop(LinkStack &S)
{
char e;
if(S==NULL) return ERROR;
e=S->data;
p=S;
S=S->next;
delete p;
return e;
}
ElemType GetTop(LinkStack S)
{
if(S!=NULL)
return S->data;
}
int ln(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#')
return 1;
else
return 0;
}
char Precede(char t,char ch)
{
switch(ch)
{
case '(':
{
return '<';
break;}
case '*':
{
if(t=='+'||t=='('||t=='-'||t=='#')
return '<';
else
return '>';
break;}
case '/':
{
if(t=='+'||t=='('||t=='-'||t=='#')
return '<';
else
return '>';
break;}
case '+':
{
if(t=='#'||t=='(')
return '<';
else
return '>';
break;}
case '-':
{
if(t=='#'||t=='(')
return '<';
else
return '>';
break;}
case ')':
{
if(t!='(')
return '=';
break;}
case '#':
{
if(t!='#')
return '>';
break;}
}
}
int Operate(int a,char c,int b)
{
int t;
switch(c)
{
case '+':
t=a+b;break;
case '-':
t=a-b;break;
case '*':
t=a*b;break;
case '/':
t=a/b;break;
}
return t;
}
int EvaluateExpression()
{
InitStack(OPND);
InitStack(OPTR);
Push(OPTR,'#');
char ch,theta,a,b;
int a1,b1,t;
cin>>ch;
while(ch!='#' || GetTop(OPTR)!='#')
{
if(!ln(ch))
{
Push(OPND,ch);
cin>>ch;}
else{
switch(Precede(GetTop(OPTR),ch))
{
case'<':
{
Push(OPTR,ch);
cin>>ch;
break;}
case'>':
{
theta=Pop(OPTR);
a=Pop(OPND);
b=Pop(OPND);
a1=a-'0';
b1=b-'0';
Push(OPND,Operate(b1,theta,a1)+'0');
break; }
case'=':
{
a=Pop(OPND);
b=Pop(OPND);
theta=Pop(OPTR);
a1=a-'0';
b1=b-'0';
Push(OPND,Operate(b1,theta,a1)+'0');
Pop(OPTR);
cin>>ch;
break;}
}
}
}
printf("计算结果为:%d",GetTop(OPND)-'0');
}
main()
{
printf("请输入要计算的表达式:");
EvaluateExpression();
}