Source:
Data Structures and Algorithm Analysis in C
The second edition (English version)
P87 3.19
Requirement:
write a program to evaluate a postfix expression
Analysis:
Usually what we do to evaluate a postfix expression is to use a link list to implement a stack. However, if by this way, the code should at least contain a structure, pop and push which makes the code long. Actually a array is enough to solve this question.(if possible, i will add the link-list version later)
Answer:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int num[100];
int ptr;
int main(void){
char temp[10];
while(scanf("%s",temp)!=EOF){
switch(temp[0]){
case '+':
ptr -= 2;
num[ptr] = num[ptr] + num[ptr+1];
ptr++;
break;
case '-':
ptr -= 2;
num[ptr] = num[ptr] - num[ptr+1];
ptr++;
break;
case '*':
ptr -= 2;
num[ptr] = num[ptr] * num[ptr+1];
ptr++;
break;
case '/':
ptr -= 2;
num[ptr] = num[ptr] / num[ptr+1];
ptr++;
break;
default:
num[ptr++] = atoi(temp);
break;
}
}
printf("%d\n",num[0]);
return 0;
}