#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define ADD(x) (x == '+')
#define SUB(x) (x == '-')
#define ADD_SUB(x) (ADD(x) || SUB(x)) /* add or subtract*/
#define DIV(x) (x == '/')
#define MUL(x) (x == '*')
#define DIV_MUL(x) (DIV(x) || MUL(x)) /* divison or multiple*/
#define OPERATOR(x) (DIV_MUL(x) || ADD_SUB(x)) /* operator */
#define LP(x) (x == '(') /* left parentheses*/
#define RP(x) (x == ')') /* right parentheses*/
#define PAREN(x) (LP(x) || RP(x)) /* parentheses*/
#define OPSIGN(x) (PAREN(x) || OPERATOR(x))
void die(char *err)
{
perror(err);
exit(EXIT_FAILURE);
}
struct stack;
typedef struct stack stack;
typedef struct stack* stackptr;
struct stack{
char oprand;
stackptr next;
};
void push(stackptr *top, char oprand);
char pop(stackptr* top);
int empty(stackptr top);
void popall(stackptr *top);
void list(stackptr top)
{
while(top) {
printf("%3c", top->oprand);
top = top->next;
}
printf("\n");
}
int main(void)
{
stack *top = NULL;
char op;
while((op = getchar()) != '\n') {
if (isdigit(op)) {
printf("%c", op);
continue;
}
if(OPERATOR(op))
putchar(' ');
if (DIV_MUL(op)) {
if (empty(top)) {
push(&top, op);
} else if (ADD_SUB(top->oprand)) {
push(&top, op);
} else if (DIV_MUL(top->oprand)) {
printf("%c ", pop(&top));
push(&top, op);
} else {
push(&top, op);
}
}
if (ADD_SUB(op)) {
if (empty(top)) {
push(&top, op);
} else if (DIV_MUL(top->oprand)) {
while(top && OPERATOR(top->oprand)) {
printf("%c ", pop(&top));
}
push(&top, op);
} else if (ADD_SUB(top->oprand)) {
printf("%c ", pop(&top));
push(&top, op);
} else {
push(&top, op);
}
}
if (PAREN(op)) {
if (empty(top) || LP(op)) {
push(&top, op);
} else if (RP(op)) {
putchar(' ');
while(top && OPERATOR(top->oprand)) {
printf("%c ", pop(&top));
};
pop(&top); /* pop left parentheses */
}
}
}
popall(&top);
putchar('\n');
return 0;
}
void push(stackptr *top, char oprand)
{
stackptr item = malloc(sizeof(stack));
if (item == NULL)
die("push() failed");
item->oprand = oprand;
item->next = *top;
*top = item;
}
char pop(stackptr *top)
{
if (*top == NULL)
die("pop() failed");
stackptr item = *top;
char oprand = item->oprand;
*top = item->next;
free(item);
return oprand;
}
void popall(stackptr *top)
{
putchar(' ');
while(*top) {
printf("%c ", pop(top));
}
}
int empty(stackptr top)
{
return top == NULL;
}
请指示