#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct listStack { int data; struct linkStack* next; }liskStack, * linkStack; void initStack(linkStack* s) { s = (linkStack)malloc(sizeof(liskStack)); (s)->next = NULL; return; } int StackEmpty(linkStack s) { return (s->next == NULL); } void push(linkStack s, int e) { linkStack p = (linkStack)malloc(sizeof(liskStack)); if (!p) exit(-1); p->data = e; p->next = s->next; s->next = p; return; } int pop(linkStack s, int e) { if (s->next == NULL) return -1; linkStack p = s->next; s->next = p->next; e = p->data; free§; return 0; } int GetTop(linkStack s) { linkStack p = s->next; if (p == NULL) return -1; return p->data; } void DestoryStack(linkStack s) { linkStack p = s->next, pp; while § { pp = p->next; free§; p = pp; } free(s); } int isNumber(char c) { if (c >= ‘0’ && c <= ‘9’) return 1; return 0; } char isPriority(char a, char b) { char ap[][8] = { “>><<<>>”,">><<<>>",">>>><>>",">>>><>>","<<<<<=?",">>>> >>","<<<<< =" }; return ap[Sacrifice(a)][Sacrifice(b)]; } int Sacrifice(char c) { switch ? { case ‘+’:return 0; case ‘-’:return 1; case '’:return 2; case ‘/’:return 3; case ‘(’:return 4; case ‘)’:return 5; case ‘#’:return 6; default:exit(-1); } } int operationResult(int a, char c, int b) { switch ? { case ‘+’:return a + b; case ‘-’:return a - b; case '’:return a * b; case ‘/’:return a / b; default:exit(-1); } } int main() { linkStack ld, lc; initStack(&ld); initStack(&lc); linkStack p = (linkStack)malloc(sizeof(liskStack)); push(lc, ‘#’); char c; c = ‘1’; int e; c = getchar(); while (c != ‘#’ || GetTop(lc) != ‘#’) { if (isNumber?) { int d = 0; while (isNumber?) { d = d * 10 + c - ‘0’; c = getchar(); } push(ld, d); continue; } else { int p1, p2; switch (isPriority(GetTop(lc), c)) { case ‘<’: push(lc, c); c = getchar(); break; case ‘>’: pop(lc, &e); pop(ld, &p2); pop(ld, &p1); push(ld, operationResult(p1, e, p2)); if (isPriority(GetTop(lc), c) == ‘>’) continue;
if (GetTop(lc)=='(' && c == ')') {
&e); c = getchar(); continue; } if (c != ‘#’) { push(lc, c); c = getchar(); } break; case ‘=’: pop(lc, &e); pop(lc, &e); break; default:exit(-1); } } } printf("%d", GetTop(ld)); return 0; }
|