写一个管理学生成绩的链表,引发了访问异常冲突,不知道是怎么回事。。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#pragma warning(disable:4996)
#define LEN sizeof(struct student) //student结构的大小
struct student* creat(); //创建链表
void print(struct student* head); //打印链表
struct student* del(struct student* head, int num); //删除链表节点
struct student* add(struct student stu_1, struct student* head); //插入链表节点
//struct student *add(int num, float score, struct student *head); //插入链表节点
struct student
{
int num;
float score;
struct student* next;
};
int n; //全局变量,用来记录存放了多少数据
void main()
{
int num;
float score;
struct student stu_1;
struct student* stu, * stu_2;
stu = creat();
print(stu);
printf("\n\n");
#if(0)
printf("输入想要删除的数据的学号:");
scanf("%d", &num);
stu = del(stu, num);
print(stu);
// system("pause");
#endif
#if(1)
printf("输入想要增加的数据的学号和成绩:");
scanf("%d%f", &stu_1.num, &stu_1.score);
stu_1.next = NULL;
#endif
stu_2 = add(stu_1, stu);
print(stu_2);
}
struct student* creat()
{
struct student* head;
struct student* p1, * p2;
p1 = p2 = (struct student*)malloc(LEN); //LEN是student结构的大小
printf("Please enter the num :");
scanf("%d", &p1->num);
printf("Please enter the score:");
scanf("%f", &p1->score);
head = NULL;
n = 0;
#if(0)
if (n == 0)
{
head = p1;
}
#endif
while (p1->num)
{
n++;
#if(1)
if (n == 1)
{
head = p1;
}
#endif
// {
p2->next = p1;
p2 = p1;
// }
p1 = (struct student*)malloc(LEN);
printf("Please enter the num :");
scanf("%d", &p1->num);
printf("Please enter the score:");
scanf("%f", &p1->score);
}
p2->next = NULL;
return head;
}
void print(struct student* head)
{
#if(1)
struct student* stu_3;
stu_3 = head;
#endif
printf("There are %d records !\n", n);
while (stu_3)
{
printf("学号为%d的学生的成绩是: %f\n", stu_3->num, stu_3->score);
stu_3 = stu_3->next;
}
}
#if(0)
void print()
{}
#endif
struct student* del(struct student* head, int num)
{
struct student* p1, * p2;
p1 = p2 = head;
if (p1)
{
while (p1->next != NULL && p1->num != num)
{
p2 = p1;
p1 = p1->next;
}
if (head->num == num)
{
head = p1->next;
n--;
}
else if (p1->num == num)
{
p2->next = p1->next;
n--;
}
else
{
printf("未找到要删除的数据!\n");
}
return head;
}
else
{
printf("这是一个空表!\n");
}
}
struct student* add(struct student stu_1, struct student* head)
{
struct student* p0, * p1, * p2;
p0 = NULL;
#if(0)
struct student stu;
stu.num = num;
stu.score = score;
#endif
p0 = &stu_1;
p2 = p1 = head;
#if(0)
stu.num = num;
stu.score = score;
p0 = &stu;
#endif
if (p1)
{
while (p0->num > p1->num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (p0->num <= head->num)
{
p0->next = head;
head = p0;
}
else if (p0->num <= p1->num)
{
p0->next = p1;
p2->next = p0;
}
else
{
p0->next = NULL;
p1->next = p0;
}
}
else
{
printf("这是一个空表!");
p0->next = NULL;
head = p0;
}
n++;
return head;
}
想要在表头插入数据发生错误。