表达式求值是源代码(栈)

[复制链接]
查看11 | 回复0 | 2007-10-17 13:33:05 | 显示全部楼层 |阅读模式
#include#include#includetypedef struct Fnode/*符号单链表*/{int yxj;char fh;struct Fnode *next;}Fnode;void F_push(Fnode *h,char c)/*尾插*/{Fnode *p;p=(Fnode*)malloc(sizeof(Fnode));p->fh=c;p->next=NULL;if(c=='+'||c=='-')p->yxj=1;else if(c=='*'||c=='/')p->yxj=2;else if(c=='('||c==')')p->yxj=0;else{ free(p); return;}while(h->next!=NULL)h=h->next;p->next=h->next;h->next=p;}char F_pop(Fnode *h)/*尾删*/{char c;while(h->next->next!=NULL)h=h->next;c=h->next->fh;free(h->next);h->next=NULL;return c;}int F_look(Fnode *h){while(h->next!=NULL)h=h->next;return h->yxj;}/*------------------------------------------------------------*/typedef struct Snode/*数字单链表*/{double data;struct Snode *next;}Snode;void S_push(Snode *h,double c)/*尾插*/{Snode *p;p=(Snode*)malloc(sizeof(Snode));p->data=c;p->next=NULL;while(h->next!=NULL)h=h->next;p->next=h->next;h->next=p;}double S_pop(Snode *h)/*尾删*/{double i;while(h->next->next!=NULL)h=h->next;i=h->next->data;free(h->next);h->next=NULL;return i;}/*-------------------------------------------------------*/char *change(char *str)/*字符串前加(,后加 )*/{char *r;*(str-1)='(';str--;r=str;strcat(r,")");return r;}/*;-------------------------------------------------*/double final(char *str,Fnode *fh,Snode *sh)/*计算表达式结果*/{double i,temp,emp;while(*str!='\0'){if(*str=='('){F_push(fh,*str);str++;continue;}else if(*str>='0'&&*str='0'&&*str='0'&&*str='0'&&*strF_look(fh))F_push(fh,*str);else{switch(F_pop(fh)){case '+':emp=S_pop(sh);S_push(sh,(S_pop(sh)+emp));break;case '-':emp=S_pop(sh);S_push(sh,(S_pop(sh)-emp));break;case '*':emp=S_pop(sh);S_push(sh,(S_pop(sh)*emp));break;case '/':emp=S_pop(sh);S_push(sh,(S_pop(sh)/emp));break;default :;}F_push(fh,*str);}str++;continue;}}return S_pop(sh);}main(){Fnode *fh;Snode *sh;char *str;fh=(Fnode*)malloc(sizeof(Fnode));fh->next=NULL;sh=(Snode*)malloc(sizeof(Snode));sh->next=NULL;str=change(gets(str));printf("%lf",final(str,fh,sh));getch();}参考资料:wan

已赞过已踩过<
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行