逆波兰表达式
以输入正确的逆波兰表达式为前提,计算结果。。。
#define MAXSIZE 10 typedef struct Node { double data; struct Node *next; }Node; typedef struct Stack { Node *top; }Stack; void s_push(Stack *s, double data); void s_pop(Stack *s, double *d); int main() { Stack s = {NULL}; char l[MAXSIZE] = {0}; char el; double d,e; int i = 0; printf("输入逆波兰表达式,以#结尾:\n"); scanf("%c", &el); while(el!='#') { if(isdigit(el) || el == '.') { l[i] = el; l[i+1] = '\0'; } if(el == ' ') { if(l[0]) { s_push(&s, atof(l)); l[0] = '\0'; i = 0; } } switch(el) { case '+': s_pop(&s, &e); s_pop(&s, &d); s_push(&s, d+e); break; case '-': s_pop(&s, &e); s_pop(&s, &d); s_push(&s, d-e); break; case '*': s_pop(&s, &e); s_pop(&s, &d); s_push(&s, d*e); break; case '/': s_pop(&s, &e); s_pop(&s, &d); if(e == 0) { printf("除数为0"); exit(-1); } s_push(&s, d/e); break; } scanf("%c", &el); } s_pop(&s, &d); printf("计算结果:%f", d); return 0; } void s_push(Stack *s, double data) { Node *p = (Node *)malloc(sizeof(Node)); p->data = data; p->next = s->top; s->top = p; } void s_pop(Stack *s, double *d) { Node *p = s->top; if(p == NULL) { return ; } *d = p->data; s->top = p->next; free(p); }