gpt4 book ai didi

c - 结构和链接列表问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:52 24 4
gpt4 key购买 nike

我刚刚学习了如何在 C 中使用链表。如果我使用单个结构,一切都很好,但是当我使用两个结构来正确分隔数据时,我遇到了问题。我在分配时遇到问题。我正在使用 Visual C++ Express 2010,这是完整的代码。任何人都可以向我解释哪里出了问题?多谢。这不是家庭作业。我只是想进一步了解它。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student
{
char name[20];
int num;

};

struct Node
{
struct Student data;
struct Node *next;
};


//void initList(struct Student **);
struct Node *createNode(struct Student );
void append(struct Node **, struct Student);
void traverse(struct Node *);
void destroyList(struct Node *);
int main()
{
char choice = 'y';
struct Student dat;
struct Node *head;
head = NULL;
//struct Student *tmp;
//initList(&head);
char buff[20];
while(choice != 'n')
{
scanf("%s %d", buff, &dat.num);
strcpy(dat.name, buff);
append(&head, dat);


printf("\n\nWould you like to enter another?");
fflush(stdin);
scanf("%c", &choice);
}

traverse(head);
destroyList(head);

system("PAUSE");
return 0;
}
/*
void initList(struct Student **list)
{
*list = NULL;
}
*/
struct Node *createNode(struct Student dat)
{
struct Node *temp;
temp = (struct Node *)malloc(sizeof(Node));
temp->data = dat;

return temp;
}

void append(struct Node **pos, struct Student d)
{
struct Node *node;
node = createNode(d);

if(*pos == NULL)
{
*pos = node;
}
else
{
struct Node *tmp;
tmp = *pos;
while(tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = node;

}
}

void traverse(struct Node *head)
{
struct Node *tmp;
for(tmp = head; tmp != NULL; tmp = tmp->next)
{
printf("\n %s %d\n\n", tmp->data.name, tmp->data.num);
}

}
void destroyList(struct Node *list)
{
if(list->next == NULL)
{
free(list);
}
else
{
destroyList(list->next);
free(list);
}
printf("\n\nList has been destroyed.\n");
}

最佳答案

createNode() 中,您应该将 next 成员设置为 NULL;或者甚至在 append() 中,如果它让你感觉更好的话:)

关于c - 结构和链接列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489812/

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