用栈 实现字符串的后缀

mac2023-05-27  19

Infix Postfix Prefix ab+c/d abcd/+ +ab/cd a(b+c)/d abc+d/ /a+bcd a(b+c/d) abcd/+ *a+b/cd

遇到 比自己高 的运算符 ,输出高阶。

#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERR -1 #define MAX 100 char stack[MAX]; int top=0; int push(char a) { if(top<MAX) { stack[++top]=a; return 0; } else { printf("The stack is full"); return ERR; } } int pop() { char var; if(stack[top]!=NULL) { var=stack[top--]; return var; } else printf("The stack is empty!\n"); return ERR; } int main() { char arr[MAX]; scanf("%s",&arr); int K,i,j,k; K=(int *)strlen(arr); k=K+2; char a[MAX]; for(i=0;i<K;i++) { j=i+1; a[j]=arr[i]; } a[0]='('; a[k-1]=')'; //printf("%s\n",a); for(i=0;i<k;i++) { if(a[i]>='a'&&a[i]<='z') { printf("%c",a[i]); } else if(a[i]=='(') { push(a[i]); } else if(a[i]=='+'||a[i]=='-') { while(stack[top]=='*'||stack[top]=='/'||stack[top]=='^') { printf("%c",stack[top]); pop(); } if(stack[top]!='*'&&stack[top]!='/'&&stack[top]!='^') { push(a[i]); } } else if(a[i]=='*'||a[i]=='/') { while(stack[top]=='^') { printf("%c",stack[top]); pop(); } if(stack[top]!='^') { push(a[i]); } } else if(a[i]=='^') { push(a[i]); } else if(a[i]==')') { while (stack[top] != '(') { printf("%c", stack[top]); pop(); } top--; } } }
最新回复(0)