马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Danmoits 于 2021-1-1 15:00 编辑
测试输入:
2 1 + 3 *
预期输出:
9
解释:
该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct stack_t stack_t, *pstack_t, snode_t, *psnode_t;
struct stack_t { psnode_t next; int v; };
stack_t STACK(void);
int isempty (pstack_t stack);
int top (pstack_t stack);
int pop (pstack_t stack);
void push (pstack_t stack, int v);
int main(void)
{
stack_t opnds = STACK();
int operand, a, b;
char input[32];
while (scanf("%s", input) != EOF) {
if (sscanf(input, "%d", &operand)) {
push(&opnds, operand);
} else {
b = pop(&opnds);
a = pop(&opnds);
switch (input[0]) {
case '+': push(&opnds, a + b); break;
case '-': push(&opnds, a - b); break;
case '*': push(&opnds, a * b); break;
case '/': push(&opnds, a / b); break;
}
}
}
printf("%d", pop(&opnds));
return 0;
}
stack_t STACK(void) { return (stack_t){ NULL }; }
int isempty (pstack_t stack) { return stack->next == NULL; }
int top (pstack_t stack) { return isempty(stack) ? -1 : stack->next->v; }
int pop (pstack_t stack) {
if (isempty(stack)) return -1;
psnode_t p = stack->next;
int v = p->v;
stack->next = p->next;
free(p);
return v;
}
void push (pstack_t stack, int v) {
psnode_t p = (psnode_t)malloc(sizeof(snode_t));
p->v = v;
p->next = stack->next;
stack->next = p;
}
请简单说下思路,并加尽可能详细的注释,谢谢 |