gpt4 book ai didi

c - 链表: Inserting a name and id number to list

转载 作者:行者123 更新时间:2023-11-30 19:44:19 24 4
gpt4 key购买 nike

需要帮助将姓名和 ID 号插入列表。每当尝试时都会崩溃将数字添加到列表中

struct node {

int id;
char name[50];
struct node *next;
} *head;


struct node *insert(struct node * list, char nam[50], int id){

struct node *helper;
struct node *pNew;
pNew=(struct node*)malloc(sizeof(struct node));

strcpy(pNew->name, nam);
pNew->id = id;
pNew->next=NULL;

helper=list;

if (list == NULL)
return pNew;

while (helper->next!=NULL)
helper=helper->next;

helper->next=pNew;


return list;

}

int main()
{

char nameInsert[50];
char nameDelete[50];
int idNum, i;
struct node *n=NULL;

//beginning of linked list, must initialize
head = NULL;

//read in data using file input function
readDataFile();

//display data operations using while loop
while(1)
{
printf("\nData Operations\n");
printf("\n--------------\n");
printf("1. Insert Name\n");
printf("2. Display Names\n");
printf("3. Delete by ID Number\n");
printf("4. Delete by Name\n");
printf("5. Exit\n");
printf("Please enter a command: ");

if(scanf("%d", &i) <= 0)
{
printf("Not valid input, please use integers 1 - 5");
exit(0);
}
else
{
//beginning of switch case
switch(i)
{
case 1:
printf("Enter the name you would like to insert: ");
scanf("%s",nameInsert);
printf("Enter the ID number associated with the name: ");
scanf("%d", &idNum);
insert(n,nameInsert, idNum); //insert function
break;

读取数据文件并将数据存储为链接列表的应用程序。提示用户输入学生姓名提示用户输入学生 ID 号用数据填充链表节点的实例将新节点添加到现有链表

最佳答案

我简化并修改了您的 insert() 函数

struct node *insert(struct node * list, char *nam, int id){
struct node *pNew;
pNew=malloc(sizeof(struct node));
if (pNew == NULL) {
printf ("Unable to allocate memory\n")
exit (1);
}
strncpy(pNew->name, nam, 49); // limit the string copy length
pNew->name[49] = 0; // precautionary terminator
pNew->id = id;
pNew->next = list; // point to list passed
return pNew; // return new list
}

调用 insert() 的方式会忽略它的返回值,即新的列表头/根。

n = insert(n, nameInsert, idNum);   // use the return value

关于c - 链表: Inserting a name and id number to list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399278/

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