gpt4 book ai didi

c - 如何从此列表中删除节点然后打印它?

转载 作者:行者123 更新时间:2023-11-30 16:31:52 26 4
gpt4 key购买 nike

主要思想:制​​作一个食物+卡路里的列表,打印它,询问要删除的条目,然后打印包含已删除条目的列表。似乎无法使其工作。

我最初只想打印初始列表,但后来决定还要求用户删除特定条目并再次打印列表。这是我未能使其发挥作用的地方。

编译器给出的错误是:

1.[Error] 'struct info' has no member named 'current'(lines 91 and 99 in function deleteNode)
2.[Error] dereferencing pointer to incomplete type (in function 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.[Error] 'struct info' has no member named 'current'(lines 91 and 99 in function deleteNode)

看看这个声明:

struct info {
int calories;
char name[100];
struct info *next;
};

然后你有一个像这样的变量声明:

struct info* temp = *s

你尝试像这样使用它:

temp->current

但是info结构中没有名称current。还有其他三个名字。您需要决定其中哪一个最适合您想要做的事情。

2.[Error] dereferencing pointer to incomplete type (in function printList)

看这行代码:

void printList(struct list *info)

您没有声明struct list,并且您正在声明一个名为info变量,它与struct info不同 您已经声明了。相反,你需要这样的东西:

void printList(struct info* list)

这声明了一个名为list的参数,它是一个指向struct info的指针。现在,在 printList() 函数中只要有 info,就需要说 list

关于c - 如何从此列表中删除节点然后打印它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50395710/

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