【发布时间】:2018-05-16 06:57:45
【问题描述】:
这是我尝试编写一个可以将任何中缀表达式转换为后缀格式的程序。我将 -1 分配给顶部以指示堆栈为空。 push时top递增,pop时top递减。但是,当我输入a+b 时,输出只给我ab 没有+ 运算符,而当我输入(a+b) 时,它显示分段错误。我认为我的堆栈有问题,但无法弄清楚出了什么问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define SIZE 30
typedef struct Stack
{
int top;
int capacity;
char* storage;
} stack;
int isEmpty(stack* a);
char topelement(stack* a);
char pop(stack* a);
void push(stack* a,char b);
bool isOperand(char a);
int Precedence(char a);
stack* NewStack(char* a);
void InfixPostfix(char* a);
int main(void)
{
char expression[SIZE];
printf("Please enter an expression:");
scanf("%s",expression);
InfixPostfix(expression);
printf("\n");
}
int isEmpty(stack* a)
{
if(a->top==-1)
{
return 1;
}
else
return 0;
}
char topelement(stack* a)
{
return a->storage[a->top];
}
char pop(stack* a)
{
if(isEmpty(a)==1)
{
printf("Stack is Empty\n");
return '$';
}
else
return a->storage[a->top];
--(a->top);
}
void push(stack* a,char b)
{
++(a->top);
a->storage[a->top]=b;
}
bool isOperand(char a)
{
if ( (a >= 'a' && a<= 'z') ||(a>='A' && a<='Z'))
{
return 1;
}
else
return 0;
}
int Precedence(char a)
{
if(a=='+' || a=='-')
{
return 1;
}
if(a=='*' || a=='/')
{
return 2;
}
if(a=='^')
{
return 3;
}
else
return -1;
}
stack* NewStack(char* a)
{
stack* b= malloc(sizeof(stack));
if(b!=NULL)
{
b->top=-1;
b->storage=malloc((strlen(a))*sizeof(char));
return b;
}
else
return NULL;
}
void InfixPostfix(char* a)
{
int i; int j=-1;
stack* b=NewStack(a);
if(b!=NULL)
{
for(i=0; i<strlen(a) ;i++)
{
if(isOperand(a[i]))
{
a[++j]=a[i];
}
if(a[i]=='(')
{
push(b, a[i]);
}
if(a[i]==')')
{
while(isEmpty(b)==0 && topelement(b)!= '(')
{
a[++j]= pop(b);
}
}
else
{
while(isEmpty(b)==0 && Precedence(a[i]) <= Precedence(topelement(b)))
{
a[++j]=pop(b);
push(b,a[i]);
}
}
}
while(isEmpty(b)==0)
{
a[++j]=pop(b);
}
a[++j]='\0';
printf("%s",a);
}
}
【问题讨论】:
-
您可能想阅读以下内容:How to debug small programs
-
b->storage=malloc((strlen(a))*sizeof(char));你似乎缺少分配一个char来保存0-终止符。 -
b->storage=malloc((strlen(a)+1)*sizeof(char));它是否正确?我已经尝试过了,它仍然无法正常工作:(
-
在给出 cmets/answers 后不要更改代码,因为这会使它们难以理解。添加更新。不过,我回滚了你上次的更改。
-
还是不行。你能看一下吗?
标签: c stack postfix-notation infix-notation