使用C中的具体堆栈来评估表达式(使用后缀表示法)



如果用户输入235+*,结果将为16。

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Stacks
{
int top;
unsigned cap;
int* array;
};
struct Stacks* createStacks(unsigned cap)
{
struct Stacks* stack = malloc(sizeof(struct Stacks));
stack->cap = cap;
stack->top = -1;
stack->array = malloc(stack->cap * sizeof(int));
return stack;
}
int isEmpty(struct Stacks* stack)
{
return stack->top == -1;
}
int isFull(struct Stacks* stack)
{
return stack->top == stack->cap - 1;
}
void push(struct Stacks* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d has been pushed to stackn", item);
}
int pop(struct Stacks* stack)
{
if (isEmpty(stack))
return 0;
return stack->array[stack->top--];
}
int showTop(struct Stacks* stack)
{
if (isEmpty(stack))
return 0;
return stack->array[stack->top];
}
int isOperand(char ch)
{
if ((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z'))
return 1;
else
return 0;
}
int main()
{
struct Stacks* stack = createStacks(MAX);
char postfix[MAX], ch;
int i = 0, op1, op2, result, m;
printf("Please enter a postfix expression: n");
fgets(postfix, MAX, stdin);
while (postfix[i] != '')
{
ch = postfix[i];
if (isOperand(ch) == 1)
{
printf("Enter the value of %c:", ch);
scanf("%d", &m);
push(stack, m);
}
else
{
op2 = pop(stack);
op1 = pop(stack);
switch (ch)
{
case '+': result = op1 + op2;
push(stack, result);
break;
case '-': result = op1 - op2;
push(stack, result);
break;
case '*': result = op1 * op2;
push(stack, result);
break;
case '/': result = op1 / op2;
push(stack, result);
break;
}
}
i++;
}
printf("nThe result is %d", showTop(stack));
return EXIT_SUCCESS;
}

下面是输出:

Please enter a postfix expression: 
abc+*
Enter the value of a:2
2 has been pushed to stack
Enter the value of b:3
3 has been pushed to stack
Enter the value of c:5
5 has been pushed to stack 
8 has been pushed to stack
16 has been pushed to stack
The result is 0

有人能帮我解释一下为什么结果不正确吗。

当您调用fgets时,结果中会包含一个换行符(如果空间可用(。这导致postfix中有六个字符,而不是五个。当最后一个换行符被处理时,您从堆栈中弹出两个值(第二个堆栈为空(,并且不推送任何新值。当你在最后打印结果时,你有一个空堆栈。

switch (ch)语句中添加一些验证以报告意外字符,并添加一些代码以忽略正在分析的表达式中的空格(空格、制表符、换行符(。

最新更新