尾插法,tail_add寻找尾节点显示访问异常,67行
#include<winuser.inl>#include<stdio.h>
#include <cstdlib>
#include<string.h>
//输入学生的总人数以及每个学生的姓名成绩,并将内容打印出来
//用尾巴插法向链表里面添加元素
void getInput(struct Student* stu);
void printfInfo(struct Student** head);
void releaseMemory(struct Student** head);
void tail_add(struct Student** head);
struct Student
{
char name;
int score;
struct Student* next;
};
void getInput(struct Student* stu)
{
printf("name:");
scanf_s("%s", stu->name, 20);
printf("score:");
scanf_s("%d", &stu->score);
}
void printfInfo(struct Student** head)
{
struct Student* stu;
stu = *head;
while (stu != NULL)
{
printf("name: %s \n", stu->name);
printf("score:%d \n", stu->score);
stu = stu->next;
}
}
void releaseMemory(struct Student** head)
{
struct Student* stu, * temp;
stu = *head;
while (stu != NULL)
{
temp = stu;
stu = stu->next;
free(temp);
}
}
void tail_add(struct Student** head)
{
struct Student* stu, * temp;
stu = (struct Student*)(malloc(sizeof(struct Student)));
if (stu == NULL)
{
printf("memory failed");
exit(1);
}
getInput(stu);
if (*head != NULL)
{
temp = *head;
//找尾节点
while (temp->next != NULL)
{
temp = temp->next;
};
//插入数据
temp = stu;
stu->next = NULL;
}
else
{
*head = stu;
stu->next = NULL;
}
}
int main()
{
struct Student* namelist = NULL;////初始化一个指针,头指针,相当于定义了一个空的单链表
struct Student* stu = NULL;
int num;
printf("total num of stu:");
scanf_s("%d", &num);
printf("\n");
printf("enter info:\n");
for (int i = 0; i < num; i++)
{
tail_add(&stu);
}
printf("finish entering!\n");
printf("begining to print\n");
printfInfo(&stu);
releaseMemory(&namelist);
return 0;
}
第 73 行
temp = stu ;
改为
temp -> next = stu ;
页:
[1]