gpt4 book ai didi

c - Infix to Postfix 程序无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 19:31:58 25 4
gpt4 key购买 nike

这是我尝试编写一个程序,可以将任何中缀格式的表达式转换为后缀格式。我将 -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);

}


}

最佳答案

除了已经建议的 malloc 更正之外,还有一些需要进行的修正。

  • pop()中有

        return a->storage[a->top];
    --(a->top);

    未到达最后一行代码的地方;将其更改为 return a->storage[a->top--];

  • InfixPostfix() 中,if(a[i]=='(')if 之前缺少 else (a[i]==')')
  • InfixPostfix()中,循环之后

                    while(isEmpty(b)==0 && topelement(b)!= '(')
    {
    a[++j]= pop(b);
    }

    a pop(b); 丢失 - 元素 '(' 也必须从堆栈中删除。

  • InfixPostfix() 中,push(b,a[i]); 必须从循环中删除

                    while(isEmpty(b)==0 && Precedence(a[i]) <= Precedence(topelement(b)))
    {
    a[++j]=pop(b);
    push(b,a[i]);
    }

    并放置在该循环之后 - a[i] 中的运算符只需放入堆栈一次。

关于c - Infix to Postfix 程序无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com