首页 > 解决方案 > 使用 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 stack\n", 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] != '\0')
    {
        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

有人可以帮我解释为什么结果不正确,谢谢。

标签: c

解决方案


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

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


推荐阅读