自己编的中缀表达式转后缀表达式(C语言),供参考,指证

来源:互联网 发布:i苹果助手官方下载mac 编辑:程序博客网 时间:2024/05/18 00:27
#include"stdio.h"#include"malloc.h"#include"string.h"#include"stdlib.h"#define MAX 100char string1[MAX];char string2[MAX];typedef struct LNode{char a;struct LNode *next;}StackNode;typedef struct{StackNode *top;}LinedkStack;void InitStack(LinedkStack &S){S.top=(StackNode *)malloc(sizeof(StackNode));S.top=0;}void push(LinedkStack &S,char e){StackNode *p;p = (StackNode *)malloc(sizeof(StackNode));p->a=e;p->next=NULL;p->next=S.top;S.top=p;}int pop(LinedkStack &S){StackNode *p;char e;if(NULL!=S.top){p=S.top;e=p->a;S.top=p->next;free(p);return 1;}elsereturn 0;}char read(LinedkStack &L){char e;if(L.top!=NULL){e=L.top->a;}else {e='#';}return e;}typedef struct{double data[MAX];int top;}SeqStack;void InitStack(SeqStack &S){                                                                                                       S.top=0;}void SeqPush(SeqStack &S,double e){if(S.top>MAX){printf("栈已满!\n");}elseS.data[S.top]=e;S.top++;}double SeqPop(SeqStack &S)  {double e;if(S.top==0){printf("栈为空!\n");}else {S.top--;e=S.data[S.top];}return e;}int set(char e){int p;switch(e){case '#':p=1;break;case '(':p=2;break;case '+':case '-':p=3;break;case '*':case '/':case '%':p=4;break;case ')':p=5;break;default:printf("你输入的符号不存在,请从新输入!\n");gets(string1);break;}return p;}void fix(char b[],char c[]){LinedkStack L;char ch,ca;int i=0,j=0,k,d,m;InitStack(L);push(L,'#');m=strlen(b);ch=b[i];i++;for(;i<=m;){ca=read(L);if(ch<'0'||ch>'9'){k=set(ch);d=set(read(L));if(k>d){if(ch==')'){ca=read(L);j--;while(ca!='('){pop(L);j++;c[j]=ca;j++;c[j]=',';ca=read(L);}pop(L);ch=b[i];i++;j++;}else {push(L,ch);ch=b[i];i++;}}else{if(ch!='('){ca=read(L);c[j]=ca;j++;c[j]=',';j++;pop(L);continue;}push(L,ch);ch=b[i];i++;}}else {while(ch>='0'&&ch<='9'){c[j]=ch;j++;ch=b[i];i++;}c[j]=',';j++;}}ca=read(L);while(ca!='#'){c[j]=ca;j++;c[j]=',';j++;pop(L);ca=read(L);}c[--j]='\0';}double cal(char b[]){SeqStack S;InitStack(S);char ca[15];  int i=0,j=0;double x1=0,x2=0,v;while(b[i]!='\0') {if(b[i]>='0'&&b[i]<='9'&&b[i]!=','){j=0;memset(ca,'\0',sizeof(ca));while(b[i]!=','){ca[j]=b[i];i++;j++;}v=atol(ca);SeqPush(S,v);}else{v=0;switch(b[i]){case ',':break;case '+':x1=SeqPop(S);x2=SeqPop(S);v=x2+x1;SeqPush(S,v);break;case '-':x1=SeqPop(S);x2=SeqPop(S);v=x2-x1;SeqPush(S,v);break;case '*': x1=SeqPop(S);x2=SeqPop(S);v=x2*x1;SeqPush(S,v);break;case '/':x1=SeqPop(S);x2=SeqPop(S);if(x1==0.0){printf("出现除0错误,请从新输入!\n");gets(string1);}else{v=x2/x1;SeqPush(S,v);}break;case '%':int x1=SeqPop(S);int x2=SeqPop(S);v=x2%x1;SeqPush(S,v);break;}i++;}}v=SeqPop(S);return v;}void main(){int n,m;double f;char sr[MAX];printf("请输入中缀表达式:\n");gets(string1);m=strlen(sr);for(n=0;n<=m;n++){sr[n]=string1[n];if(string1[n]=='%'&&string1[n+1]=='-'){printf("求余号后面有减号,请从新输入!\n");gets(string1);}}fix(string1,string2);printf("后缀表达式:\n%s\n",string2);f=cal(string2);printf(" 计算结果:\n%lf\n",f);}

0 0
原创粉丝点击