include stdio include stdlib include malloc include assert typedef str

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef struct stack *Stack;
typedef struct node *Node;
Stack createStack();
int isEmpty(Stack stack);
int pushItem(Stack stack, char item);
char popItem(Stack stack);
int priority(char);
char *processExpression(char *expression);
struct node {
char value;
Node next;
};
struct stack {
Node head;
};
Stack createStack(){
Stack stack = malloc(sizeof(Stack));
if (stack == NULL)
return NULL;
stack->head = NULL;
return stack;
}
int isEmpty(Stack stack){
assert(stack!=NULL);
return stack->head == NULL;
}
int pushItem(Stack stack, char item){
assert(stack != NULL);
Node node = malloc(sizeof(Node));
if (node == NULL)
return 0;
node->value=item;
node->next=stack->head;
stack->head=node;
return 1;
}
char popItem(Stack stack){
assert(stack!=NULL);
if (stack->head ==NULL)
return '\n';
Node node = stack->head->next;
char item = stack->head->value;
free(stack->head);
stack->head=node;
return item;
}
int priority(char item){
switch (item){
case '*':
case '/':
return 3;
case '-':
case '+':
return 2;
case '(':
return 1;
}
}
char *processExpression(char *expression){
Stack stack = createStack();
char c;
char *output = calloc(sizeof(char),80);
int k,point;
k = point=0;
c = expression[k];
while (c!='\0'){
if (c==')'){
while (stack->head->value!='(')
output[point++]=popItem(stack);
popItem(stack);
}
if (c>='a' && c<='z')
output[point++]=c;
if (c=='(')
pushItem(stack,'(');
if (c=='+'||c=='-'||c=='*'||c=='/'){
if (isEmpty(stack))
pushItem(stack,c);
else{
while(!isEmpty(stack)&&(priority(stack->head->value)>=priority(c)))
output[point++]=popItem(stack);
pushItem(stack,c);
}
}
k++;
c = expression[k];
}
while (stack->head!=NULL)
output[point++]=popItem(stack);
output[point]='\0';
free(stack);
return output;
}
int main(){
printf("a+b=%s\n",processExpression("a+b\0"));
printf("(a+b)*(c-d)-e=%s\n", processExpression("(a+b)*(c-d)-e\0"));
printf("a+b*c/(d-e)*f=%s\n", processExpression("a+b*c/(d-e)*f\0"));
return 0;
}