用栈实现四则运算
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TRUE 1
#define FALSE 0
typedef struct LinkNODE
{
int data;
LinkNODE *next;
}LinkNode,*LinkStackPtr;
typedef struct LinkNODE1
{
char data;
LinkNODE1 *next;
}LinkNode1,*LinkStackPtr1;
typedef struct
{
LinkStackPtr top;
int count;
}LinkStack;
typedef struct
{
LinkStackPtr1 top;
int count;
}LinkStack1;
char compare(char a,char b);
int calculate(int a,int b,char op);
int EvaluateExpression();
int IsOptr(char);
void push(LinkStack *L,int m);
int pop(LinkStack *L);
int top(LinkStack *L);
void push1(LinkStack1 *L,char m);
int pop1(LinkStack1 *L);
char top1(LinkStack1 *L);
LinkStack opnd;
LinkStack1 optr;
char expression[50];
int main()
{
optr.top=NULL;
optr.count=-1;
opnd.top=NULL;
optr.count=-1;
push1(&optr,'#');
scanf("%s",expression);
int num=strlen(expression);
expression[num]='#';
printf("%d\n",EvaluateExpression());
return 0;
}
char compare(char a,char b)
{
if(a=='+' || a=='-')
{
if(b=='*' ||b=='/' ||b=='(')
return '<';
else
return '>';
}
if(a=='*' || a=='/')
{
if(b=='(')
return '<';
else
return '>';
}
if(a=='(')
{
if(b==')')
return '=';
else
return '<';
}
if(a=='#')
{
if(b=='#')
return '=';
else
return '<';
}
}
int calculate(int a,int b,char op)
{
switch(op)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
return FALSE;
}
}
int IsOptr(char c)
{
if(c=='+' ||c=='-' ||c=='*'||c=='/' ||c=='('||c==')' ||c=='#')
return TRUE;
else
return FALSE;
}
int EvaluateExpression()
{
int i=0;
int num;
while(!(expression[i]=='#'&&top1(&optr)=='#'))
{
if(!IsOptr(expression[i]))
{
num=0;
while(!IsOptr(expression[i]))
{
num*=10;
int d=expression[i]-'0';
num+=d;
++i;
}
push(&opnd,num);
}
else
{
switch(compare(top1(&optr),expression[i]))
{
case '<':
push1(&optr,expression[i]);
++i;
break;
case '=':
pop1(&optr);
++i;
break;
case '>':
{
int a=top(&opnd);
pop(&opnd);
int b=top(&opnd);
pop(&opnd);
int c=calculate(b,a,top1(&optr));
push(&opnd,c);
pop1(&optr);
}
break;
default:
break;
}
}
}
return top(&opnd);
}
void push(LinkStack *L,int m)
{
LinkNode *p;
p=(LinkNode*)malloc(sizeof(LinkNode));
p->data=m;
p->next=L->top;
L->top=p;
L->count++;
}
int pop(LinkStack *L)
{
LinkNode *p;
if(L->count==-1)
return FALSE;
p=L->top;
L->top=L->top->next;
L->count--;
free(p);
return TRUE;
}
int top(LinkStack *L)
{
if(L->count==-1)
return FALSE;
return L->top->data;
}
void push1(LinkStack1 *L,char m)
{
LinkNode1 *p;
p=(LinkNode1*)malloc(sizeof(LinkNode1));
p->data=m;
p->next=L->top;
L->top=p;
L->count++;
}
int pop1(LinkStack1 *L)
{
LinkNode1 *p;
if(L->count==-1)
return FALSE;
p=L->top;
L->top=L->top->next;
L->count--;
free(p);
return TRUE;
}
char top1(LinkStack1 *L)
{
if(L->count==-1)
return FALSE;
return L->top->data;
}
以后待解决的问题:
1.用MFC做出界面(不熟悉)
2.STL