1 #include<stdio.h>
2 #include<stdlib.h>
3
4 #define OK 1
5 #define ERROR 0
6 #define STACK_INIT_SIZE 20
7 #define STACK_INCREMENT 10
8
9 typedef char Elemtype; 10 typedef int Status; 11
12 typedef struct StackNode{ 13 Elemtype* base; 14 Elemtype* top; 15 int stackSize; 16 }StackNode; 17 typedef struct StackNode* Stack; 18
19 Status InitStack(Stack s){ 20 s->base = (Elemtype*)malloc(sizeof(Elemtype) * STACK_INCREMENT); 21 if(! s->base){ 22 return ERROR; 23 } 24 s->top = s->base; 25 s->stackSize = STACK_INIT_SIZE; 26 return OK; 27 } 28 Status Pop(Stack s,Elemtype* value){ 29 if(s->base == s->top){ 30 printf("pop ERROR\n"); 31 return ERROR; 32 } 33 *value = *(--(s->top)); 34 return OK; 35 } 36 Status Push(Stack s, Elemtype value){ 37 if(s->top - s->base == s->stackSize){ 38 s->base = (Elemtype*)realloc(s->base,sizeof(Elemtype) * (STACK_INIT_SIZE + STACK_INCREMENT)); 39 if(! s->base) 40 return ERROR; 41 s->top = s->base + STACK_INIT_SIZE; 42 s->stackSize = STACK_INCREMENT + STACK_INIT_SIZE; 43 } 44 *(s->top) = value; 45 s->top++; 46 return OK; 47 } 48 int StackLength(Stack s){ 49 return s->top - s->base; 50 } 51 //test
52 Status ShowStack(Stack s){ 53 while(s->top != s->base){ 54 printf("%c ",*(--(s->top))); 55 } 56 printf("\n"); 57 } 58
59 Status Infix2Postfix(){ //將中綴表達式轉化爲後綴表達式
60 StackNode s; 61 InitStack(&s); 62 char c; 63 char c1; 64 printf(" Please Enter Infix expression\n"); 65 printf(" -------note: number separeted by space,end of '#'\n\n"); 66 scanf("%c", &c); 67 /* Note:若是是數字: 直接輸出控制檯; 68 * 若是是*,/,(: 直接Push 69 * 若是是+,-: 則要將*,/,+,-都進行Pop,直到stack爲空或者是遇到了'(' 70 * 若是是')': 將在遇到'('以前的全部的都要Pop 71 * */
72 while('#' != c){ 73 while(c >= '0' && c <= '9'){ //若是是數字,則直接輸出
74 printf("%c", c); 75 scanf("%c", &c); 76 if( c < '0' || c > '9'){ 77 printf("%c", ' '); 78 break; 79 } 80 } 81 if('+' == c || '-' == c){ //若是是 + 或者是 -
82 if(!StackLength(&s)){ //若是stack爲空的話,直接Push
83 Push(&s,c); 84 } 85 else{ //不爲空的話須要Pop進行比較/+-*都須要Pop
86 Pop(&s,&c1); 87 while( '(' != c1 ){ 88 printf("%c ", c1); 89 if(StackLength(&s) == 0){ 90 break; 91 } 92 else
93 Pop(&s, &c1); 94 } 95 if( '(' == c1 ) 96 Push(&s, c1); 97 Push(&s, c); 98 } 99 } 100 else if('*' == c || '/' == c || '(' == c){ //若是是*或者是/
101 Push(&s, c); 102 } 103 else if( ')' == c ){ 104 Pop(&s,&c1); 105 while( '(' != c1){ 106 printf("%c ", c1); 107 Pop(&s, &c1); 108 } 109 } 110 else if( '#' == c ){ 111 break; 112 } 113 else{ 114 printf("Input Is ERROR!\n"); 115 return ERROR; 116 } 117 scanf("%c", &c); 118 } 119
120 while(StackLength(&s)){ 121 Pop(&s,&c1); 122 printf("%c ", c1); 123 } 124 return OK; 125 } 126 int main(){ 127 Infix2Postfix(); 128 /*
129 Stack s; 130 InitStack(s); 131 Push(s,'a'); 132 Push(s,'r'); 133 Push(s,'e'); 134 Push(s,'d'); 135 ShowStack(s); 136 */
137 return 0; 138 }