首页 > 代码库 > [栈和队列]从中缀向后缀转换表达式
[栈和队列]从中缀向后缀转换表达式
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define INIT_STACK_SIZE 100 5 typedef struct 6 { 7 char * chOperator; 8 int dwtop; 9 }OPND; 10 11 void InitStack(OPND *); 12 char Pop(OPND *); 13 void Push(OPND *,char ); 14 char GetTop(OPND); 15 16 char ComparePri(char op1,char op2); 17 void printStack(OPND); 18 19 char stringBuffer[128] = {‘\0‘}; 20 char stringValue[128] = {‘\0‘}; 21 int main() 22 { 23 OPND opnd; 24 int N = 0; 25 char ch ,*strValue,*strBuffer; 26 scanf("%d",&N); 27 getchar(); 28 while(N--){ 29 30 strValue =http://www.mamicode.com/ stringValue; 31 strBuffer = stringBuffer; 32 33 memset(stringValue,0,128*sizeof(char)); 34 memset(stringBuffer,0,128*sizeof(char)); 35 36 gets(stringBuffer); 37 InitStack(&opnd); 38 Push(&opnd,‘#‘); 39 40 ch = *strBuffer++; 41 while(ch != ‘#‘ || GetTop(opnd) != ‘#‘){ 42 if((ch >= ‘a‘ && ch <= ‘z‘)||(ch >= ‘A‘ && ch <= ‘Z‘)) { 43 *strValue =http://www.mamicode.com/ ch; 44 strValue++; 45 ch = *(strBuffer++); 46 } 47 else 48 switch(ComparePri(GetTop(opnd),ch)){ 49 case ‘<‘ : Push(&opnd,ch); ch = *(strBuffer++); break; 50 case ‘=‘ : Pop(&opnd); ch = *(strBuffer++); break; 51 case ‘>‘ : *strValue = http://www.mamicode.com/Pop(&opnd); strValue++; break; 52 } 53 } 54 puts(stringValue); 55 } 56 return 0; 57 } 58 void InitStack(OPND *S) 59 { 60 S->chOperator = (char *)malloc(INIT_STACK_SIZE * sizeof(char)); 61 if(!S->chOperator) exit(1); 62 S->dwtop = 0; 63 } 64 void Push(OPND *S,char ch) 65 { 66 *(S->chOperator + S->dwtop) = ch; 67 S->dwtop++; 68 } 69 char Pop(OPND *S) 70 { 71 S->dwtop--; 72 return *(S->chOperator + S->dwtop); 73 } 74 char ComparePri(char op1,char op2) 75 { 76 if((op1 == ‘+‘ || op1 == ‘-‘)&&(op2 == ‘*‘ || op2 == ‘/‘)) return ‘<‘; 77 else if((op1 == ‘(‘ && op2 == ‘)‘)||(op1 == ‘#‘ && op2 == ‘#‘)) return ‘=‘; 78 else if(op1 == ‘(‘ || op1 == ‘#‘ || op2 == ‘(‘) return ‘<‘; 79 else return ‘>‘; 80 } 81 void printStack(OPND opnd) 82 { 83 while(opnd.dwtop){ 84 opnd.dwtop--; 85 printf("%c",*(opnd.chOperator + opnd.dwtop)); 86 } 87 } 88 char GetTop(OPND opnd) 89 { 90 return *(opnd.chOperator + opnd.dwtop -1); 91 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。