|
|
发表于 2023-11-30 08:44:26
|
显示全部楼层
有几个问题可能导致输出时出错:
InitStack函数没有返回值。在函数声明中,将函数返回类型改为void即可。
在Pop函数中,当栈为空时,没有进行错误处理。可以在栈为空时添加错误处理的逻辑,例如输出错误信息或返回错误码。
在读取输入时,使用scanf("%c", &c)读取字符,但由于输入缓冲区中可能还有其他字符(如换行符),可能会导致输入不符合预期。可以在读取字符后加上空格符,如scanf(" %c", &c),以消耗掉输入缓冲区中的空白字符。
参考代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <ctype.h>
- #define STACK_INIT_SIZE 20
- #define STACKINCREMENT 10
- typedef char ElemType;
- typedef struct
- {
- ElemType *base;
- ElemType *top;
- int stacksize;
- } sqStack;
- void InitStack(sqStack *s)
- {
- s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
- if (!s->base)
- {
- exit(0);
- }
- s->top = s->base;
- s->stacksize = STACK_INIT_SIZE;
- }
- void Push(sqStack *s, ElemType e)
- {
- if (s->top - s->base >= s->stacksize)
- {
- s->base = (ElemType *)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(ElemType));
- if (!s->base)
- {
- exit(0);
- }
- }
- *(s->top) = e;
- s->top++;
- }
- int Pop(sqStack *s, ElemType *e)
- {
- if (s->top == s->base)
- {
- return 0; // 栈为空,返回错误码
- }
- *e = *(--s->top);
- return 1;
- }
- int StackLen(sqStack *s)
- {
- return (s->top - s->base);
- }
- int main()
- {
- sqStack s;
- char c, e;
- InitStack(&s);
- printf("请输入中缀表达式,以#作为结束标志:\n");
- scanf(" %c", &c);
- while (c != '#')
- {
- if (c >= '0' && c <= '9')
- {
- printf("%c", c);
- }
- else if (c == ')')
- {
- printf("%c", c);
- if (Pop(&s, &e))
- {
- printf("%c", e);
- while (e != '(' && Pop(&s, &e))
- {
- printf("%c", e);
- }
- }
- }
- else if (c == '+' || c == '-')
- {
- if (!StackLen(&s))
- {
- Push(&s, c);
- }
- else
- {
- do
- {
- if (Pop(&s, &e))
- {
- if (e == '(')
- {
- Push(&s, e);
- }
- else
- {
- printf("%c", e);
- }
- }
- else
- {
- break;
- }
- } while (StackLen(&s) && e != '(');
- Push(&s, c);
- }
- }
- else if (c == '(' || c == '*' || c == '/')
- {
- Push(&s, c);
- }
- else
- {
- printf("error!\n");
- return -1;
- }
- scanf(" %c", &c);
- }
- getchar();
- while (StackLen(&s))
- {
- if (Pop(&s, &e))
- {
- printf("%c", e);
- }
- else
- {
- break;
- }
- }
- return 0;
- }
复制代码 |
|