如何从此列表中删除节点然后将其打印出来?

时间:2018-05-17 15:50:37

标签: c list

主要想法:制作食物+卡路里列表,打印它,询问要删除的条目然后打印带有删除条目的列表。似乎无法使其发挥作用。

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

编译器给出的错误是:

  

1. [错误]'struct info'没有名为'current'的成员(函数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 个答案:

答案 0 :(得分:0)

  

1. [错误]&#39; struct info&#39;没有名为&#39; current&#39;的成员(函数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的参数,它是指向struct info的指针。现在,无论您在此info函数中printList()处都有list,您都需要说SELECT A.id, A.content as priorcontent , B.content as currcontent , A.test priorcontent2 , B.test currcontent2 FROM docs A inner JOIN docs B ON A.id = B.id and A.rev=1 and B.rev=2