c - 我怎样才能从这个列表中删除一个节点然后打印它?
问题描述
主要思想:列出食物+卡路里,打印出来,询问要删除的条目,然后打印带有已删除条目的列表。似乎无法让它工作。
我最初只想打印初始列表,但后来决定还要求用户删除特定条目并再次打印列表。这是我未能使其工作的地方。
编译器给出的错误是:
1.[错误]“结构信息”没有名为“当前”的成员(函数 deleteNode 中的第 91 和 99 行)
2.[错误] 取消引用指向不完整类型的指针(在函数 printList 中)
到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct info {
int calories;
char name[100];
struct info *next;
};
void add_info(struct info *s);
struct info *create(void);
void printList();
void deleteNode ();
int main()
{
struct info *first;
struct info *current;
struct info *new;
int x, i, y;
printf("\t\tHow many entries do you want? ");
scanf("%d",&x);
first = create();
current = first;
for(i=0;i<x;i++)
{
if(i==0)
{
first = create();
current = first;
}
else
{
new = create();
current->next = new;
current = new;
}
add_info(current);
}
current->next = NULL;
current = first;
while(current)
{
printf("\n\nCalories per food: %d\t Name of the food: %s\n",current->calories,current->name);
current = current->next;
}
printf("Which entry would you like to remove? ");
scanf("%d", &y);
deleteNode(y);
printf("The list after deletion is: ");
printfList();
return(0);
}
void add_info(struct info *s)
{
printf("Insert number of calories: ");
scanf("%d",&s->calories);
printf("\n Insert name of the food: ");
scanf("%s",&s->name);
s->next = NULL;
}
struct info *create(void)
{
struct info *initial;
initial = (struct info *)malloc(sizeof(struct info));
if( initial == NULL)
{
printf("Memory error");
exit(1);
}
return(initial);
}
void deleteNode(struct info **s, int y)
{
struct info* temp = *s, *prev;
if (temp != NULL && temp->current == y)
{
*s = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->current != y)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
void printList(struct list *info)
{
while (info != NULL)
{
printf(" %d %s ", info->calories, info->name);
info = info->next;
}
}
解决方案
1.[错误] 'struct info' 没有名为 'current' 的成员(函数 deleteNode 中的第 91 和 99 行)
看看这个声明:
struct info {
int calories;
char name[100];
struct info *next;
};
然后你有一个像这样的变量声明:
struct info* temp = *s
你尝试像这样使用它:
temp->current
但结构current
内没有名称info
。取而代之的是其他三个名称。您需要决定哪些最适合您尝试做的事情。
2.[错误] 取消引用指向不完整类型的指针(在函数 printList 中)
看这行代码:
void printList(struct list *info)
您没有声明struct list
,并且您正在声明一个名为的变量info
,该变量与您已经声明的变量不同struct info
。相反,您需要这样的东西:
void printList(struct info* list)
这声明了一个名为的参数list
,它是指向 a 的指针struct info
。现在你info
在这个printList()
函数中的任何地方,你都需要说list
。