前缀以在 C 中插入


#include<stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node{
char* data;
struct Node* next;
};
typedef struct Node NODE;

NODE* push(NODE* top, char* item){
NODE* newNode;
newNode=(NODE*)malloc(sizeof(NODE));
newNode->next=NULL;
newNode->data=item;
if(top==NULL){
top=newNode;
}
else{
newNode->next=top;
top=newNode;
}
return top;
}
char pop(NODE* top){
NODE* temp=top;
int i, returnValue;
if(top==NULL){
return top;
returnValue='';
}
else{
top=top->next;
returnValue=temp->data;
free(temp);
}
return returnValue;
}
void display(NODE* top){
NODE* temp=top;
while(temp->next!=NULL){
printf("%c",temp->data);
temp=temp->next;
}
printf("n");
}
int isOperator(char c){
switch(c)
{
case '*':
case '/':
case '+':
case '-':
return 1;
}
return 0;
}
char* prefix_to_infix(char* expression){
NODE* top;
top=(NODE*)malloc(sizeof(NODE));
top->next=NULL;
int i;
for(i=strlen(expression)-1;i>=0;i--)
{
if(isOperator(expression[i])){
char a=pop(top);
char b=pop(top);
char temp[5]={'(',a,expression[i],b,')'};
push(top,temp);
}
else{
top=push(top, expression[i]);
}
}
return top->data;
}
int main(){
NODE* top;
top=(NODE*)malloc(sizeof(NODE));
top->next=NULL;
char expression[30];
gets(expression);
puts(prefix_to_infix(expression));
}

请帮忙,我写了这个 C 代码来打印将前缀表达式转换为中缀表达式。但是代码会给出一些运行时错误。

https://www.geeksforgeeks.org/prefix-infix-conversion/以上是我用过的算法,唯一的问题是代码的实现

代码说明

我已经使用链表来创建我的堆栈。我只是在头部插入以推送和删除在头部以弹出。*为了从前缀转换为中缀,首先我将表达式(作为字符数组(作为函数 prefix_to_infix(( 的参数。

现在我正在检查表达式元素是操作数还是运算符。 ->如果操作数我把它推到堆栈中。 ->如果运算符I 弹出前两个操作数并将它们与中间的运算符合并。

问题太多,请检查如何在编译器中激活警告。

NODE* push(NODE* top, char* item){

第二个参数需要char *,但您正在传递单个char

top=push(top, expression[i]);

这也是错误的:

char pop(NODE* top){
NODE* temp=top;
int i, returnValue;
if(top==NULL){
return top; /* You can not return NULL, pop returns a char */
returnValue=''; /* This line is never reached */
}

在这里:

printf("%c",temp->data);

temp->data是一个char *,请使用"%s"作为格式说明符。

另外,不要使用gets,它不再是标准的一部分,在以前的版本中非常危险,而是使用fgets

最后,正如评论中指出的那样,不要投下malloc的结果

最新更新