[DS][3-19]Evaluate a postfix expression
Source:Data Structures and Algorithm Analysis in C
The second edition (English version)
P873.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;
int ptr;
int main(void){
char temp;
while(scanf("%s",temp)!=EOF){
switch(temp){
case '+':
ptr -= 2;
num = num + num;
ptr++;
break;
case '-':
ptr -= 2;
num = num - num;
ptr++;
break;
case '*':
ptr -= 2;
num = num * num;
ptr++;
break;
case '/':
ptr -= 2;
num = num / num;
ptr++;
break;
default:
num = atoi(temp);
break;
}
}
printf("%d\n",num);
return 0;
}
页:
[1]