中缀表达式 转后缀表达式


#include <stdio.h> #include <stdlib.h> #include <ctype.h> typedef struct Stack { char *base, *top; int size; }Sta; void init(Sta *s) { s->base =(Sta *) malloc (20*sizeof(char)); s->top = s->base; s->size = 20; } void push(Sta *s, char e) { if (s->top - s->base >= s->size) { s->base = (Sta *)realloc (s, (s->size+10)*sizeof(char)); s->size += 10; } *(s->top) = e; s->top ++; } void pop(Sta *s, char *e) { *e = *--(s->top); } int len(Sta s) { return (s.top - s.base); } int main() { Sta s; char e, d, c; init (&s); scanf("%c", &c); while (c!= '#') { while (isdigit(c)) { printf("%c", c); scanf("%c", &c); if (!isdigit(c)) printf(" "); } if (')' == c) { pop(&s, &e); while ('(' != e) { printf("%c ", e); pop(&s, &e); } } else if ('-'==c || '+'==c) { if (!len(s)) { push(&s, c); } else { do { pop(&s, &e); if ('('==e) { push(&s, e); } else { printf("%c ", e); } }while(len(s) && '(' != e); push(&s, c); } } else if ('*'==c || '/'==c || '('==c) { push(&s, c); } else if ('#'== c) { break; } scanf("%c", &c); } while (len(s)) { pop(&s, &e); printf("%c ", e); } }

猜你喜欢

转载自www.cnblogs.com/Kingpenguin/p/9968654.html