给定字符串型的算术表达式,实现中缀转后缀并运算得出结果;
1 #ifndef STACK_H_INCLUDED 2 #define STACK_H_INCLUDED 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include"stack.h" 6 #define SIZE 100 7 #define TYPE char 8 typedef struct Node* pNode; 9 typedef struct Node node; 10 typedef pNode Stack; 11 12 char postfix[SIZE]; 13 14 struct Node 15 { 16 TYPE data; 17 struct Node* next; 18 }; 19 int isEmpty(Stack s); 20 void Pop(Stack s); 21 void Push(Stack s,TYPE element); 22 TYPE Top_of_stack(Stack s); 23 Stack CreatStack(); 24 void makeEmpty(Stack s); 25 26 Stack CreatStack() 27 { 28 Stack s=(Stack)malloc(sizeof(node)); 29 s->next=NULL; 30 makeEmpty(s); 31 return s; 32 } 33 void makeEmpty(Stack s) 34 { 35 if(s==NULL) 36 printf("you need creat a stack at first"); 37 while(!isEmpty(s)) 38 Pop(s); 39 } 40 int isEmpty(Stack s) 41 { 42 return s->next==NULL; 43 } 44 void Pop(Stack s) 45 { 46 if(isEmpty(s)) 47 printf("Stack is empty"); 48 else 49 { 50 pNode temp=s->next; 51 s->next=s->next->next; 52 free(temp); 53 } 54 55 } 56 void Push(Stack s,TYPE element) 57 { 58 pNode temp=(Stack)malloc(sizeof(node)); 59 if(temp) 60 { 61 temp->data=element; 62 temp->next=s->next; 63 s->next=temp; 64 } 65 } 66 TYPE Top_of_stack(Stack s) 67 { 68 if(isEmpty(s)) 69 { 70 printf("Stack is empty"); 71 return 0; 72 } 73 else 74 return s->next->data; 75 } 76 77 78 #endif // STACK_H_INCLUDED
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include"stack.h" 4 #define SIZE 100 5 6 char postfix[SIZE]; 7 8 // if op > instack push else pop; 9 // return the priority of operator of expression minus 10 //that of stack 栈外优先级减去栈内优先级 11 int priority(char op_of_expression,char ch_in_stack) 12 { 13 int op=0; 14 int ch=0; 15 if(op_of_expression=='+'||op_of_expression=='-') 16 op=1; 17 else if(op_of_expression=='*'||op_of_expression=='/') 18 op=2; 19 else if(op_of_expression=='(') 20 op=3; 21 else 22 printf("wrong operator"); 23 24 if(ch_in_stack=='+'||ch_in_stack=='-') 25 ch=1; 26 else if(ch_in_stack=='*'||ch_in_stack=='/') 27 ch=2; 28 else if(ch_in_stack=='(') 29 ch=0; 30 else 31 printf("wrong operator"); 32 33 return op-ch; 34 } 35 int isOperator(char ch) 36 { 37 switch (ch) 38 { 39 case'+': 40 case'-': 41 case'*': 42 case'/': 43 case'(': 44 case')': 45 return 1; 46 break; 47 default: 48 return 0; 49 break; 50 } 51 } 52 void Infix_to_Pofix(char* s) 53 { 54 int index=0; 55 56 char ch; 57 Stack stack=CreatStack(); 58 makeEmpty(stack); 59 while((ch=*s)!='