簡體   English   中英

我如何從該列表中刪除一個節點然后進行打印?

[英]How can i remove a node from this list and then print it?

主要思想是:制作一份食物+卡路里的清單,將其打印出來,詢問要刪除的條目,然后使用該條目打印清單。 似乎無法使其正常工作。

我最初只想打印初始列表,但后來決定還要求用戶刪除要刪除的特定條目,然后再次打印列表。 這是我無法使其工作的地方。

編譯器給出的錯誤是:

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. [錯誤]“結構信息”沒有名為“當前”的成員(函數deleteNode中的第91和99行)

看一下這個聲明:

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

然后,您將獲得如下所示的變量聲明:

struct info* temp = *s

您嘗試像這樣使用它:

temp->current

但是info結構內部沒有current的名稱。 相反,還有其他三個名稱。 您需要確定其中哪一項最適合您要執行的操作。

2. [錯誤]取消指向不完整類型的指針(在函數printList中)

查看以下代碼行:

void printList(struct list *info)

您沒有聲明struct list並且正在聲明一個名為info變量 ,該變量與您已經聲明的struct info 相反,您需要這樣的東西:

void printList(struct info* list)

這將聲明一個名為list的參數,該參數是指向struct info的指針。 現在,在此printList()函數中您擁有info任何地方,您都需要說list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM