需要帮助在列表中插入名称和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号码使用dataAdd将新节点添加到现有链接列表中的链接列表节点的实例
答案 0 :(得分:0)
我已简化并修改了您的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