#define ST struct student
#define LEN sizeof(ST)
#define MAX 20
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
struct student
{
char num[MAX];
char name[MAX];
char sex;
int score1[MAX], score2[MAX], score3[MAX], score4[MAX];
char addr[MAX];
struct student* next;
};
ST* creat()
{
ST* head = NULL, * p1 = NULL, * p2 = NULL;
int n = 0;
p1 = p2 = (ST*)malloc(sizeof(ST));
if (p1 == NULL)
{
printf("Can't get memory!\n");
return NULL;
}
printf("输入学生信息:\n");
while (scanf_s("%s %s %c %d %d %d %d %s", p1->num, p1->name, &p1->sex,
&p1->score1, &p1->score2, &p1->score3, &p1->score4, p1->addr) != NULL)
{
n++;
if (n == 1)
{
head = p1;
}
else {
p2->next = p1;
}
p2 = p1;
if (p1 == NULL)
{
printf("Can't get memory!\n");
return NULL;
}
}
p2->next = NULL;
return head;
}
void print(ST* head)
{
ST* p = head;
if (head != NULL)
{
do {
printf("%s %s %c %d %d %d %d %s\n", p->num, p->name, p->sex,
p->score1, p->score2, p->score3, p->score4, p->addr);
p = p->next;
} while (p != NULL);
}
}
ST* insert(ST* head, char num[], ST* newstu)
{
ST* p;
p = head;
if (head == NULL)
{
head = newstu;
newstu->next = NULL;
return(head);
}
if (strcmp(num, p->num) < 0)
{
newstu->next = p;
head = newstu;
return(head);
}
while (p->next != NULL && strcmp(num, p->next->num) > 0)
{
p = p->next;
}
newstu->next = p->next;
p->next = newstu;
return(head);
}
ST* del(ST* head, char num[])
{
ST* p1, * p2=NULL;
if (head == NULL)
{
printf("\n链表为空\n");
return (head);
}
p1 = head;
while (strcmp(num, p1->num) != 0 && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (strcmp(num, p1->num) == 0)
{
if (p1 == head)
head = p1->next;
else p2->next = p1->next;
free(p1);
}
else
printf("没找到%s号\n", num);
return (head);
}
int main()
{
ST* head, * newstu;
char num[MAX];
int choice;
head = creat();
printf("输入要进行的操作:\n");
printf("1.插入\n");
printf("2.删除\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
newstu = (ST*)malloc(sizeof(ST));
printf("输入要插入的学生信息:\n");
scanf_s("%s %s %c %d %d %d %d %s", newstu->num, newstu->name, &newstu->sex,
&newstu->score1, &newstu->score2, &newstu->score3, &newstu->score4, newstu->addr);
head = insert(head, newstu->num, newstu);
printf("插入后的链表为:\n");
print(head);
break;
case 2:
printf("输入要删除的学生学号:\n");
scanf_s("%s", num);
head = del(head, num);
printf("删除后的链表为:\n");
print(head);
break;
default:
printf("输入错误!\n");
break;
}
return 0;
}
为什么在输入第一个学生的信息之后就显示异常了呢 应该怎么修改?期待回复 感谢!