输入学号和成绩到列表内,在输入学号删除相同学号的列表
# include <stdio.h># include <stdlib.h>
int n;
struct student
{
int num;
float score;
struct student *next;
};
struct student *addlist();
struct student *sublist(struct student * , int num);
void print(struct student *);
int main(void)
{
int i;
struct student *head;
head = addlist();
printf("请输入需要删除的学号,不需要输入‘0’退出\n");
scanf("%d",&i);
if(i != 0)
{
head = sublist(head ,i);
}
print(head);
}
struct student *addlist()
{
struct student *p1 , *p2 , *head;
do
{
int a ;
a =sizeof(struct student);
p1 = malloc(a);
p2 = p1;
printf("输入学号\n");
scanf("%d",&p1->num);
printf("输入成绩\n");
scanf("%f",&p1->score);
if(p1->num != 0)
{
n = n+1;
if(n == 1 )
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
}
}while (p1->num != 0);
p2->next = NULL;
returnhead;
}
struct student *sublist(struct student *head ,int num)
{
struct student *p1 ,*p2 ;
p1 = head;
if(head->num == num)
{
head = head->next;
n = n -1;
}
else
{
while (p1 != NULL)
{
p2 =p1;
p1 =p1->next;
if(p1->num == num)
{
p2->next = p1->next;
n= n-1;
break;
}
}
}
return head;
}
void print(struct student *head)
{
struct student *p1;
p1 = head;
printf("链表中共有%d\n个元素\n\n\n",n);
while (p1 != NULL)
{
printf("学号:%d成绩:%f \n",p1->num,p1->score);
p1 = p1->next;
}
}
报错:Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
求大佬们帮我看看到底哪里出了问题·····十分感谢!! 建立链表的函数有问题
struct student *addlist()
{
struct student *p1 , *p2 , *head;
do
{
int a ;
a =sizeof(struct student);
p1 = (student *)malloc(a);
//将next 赋空指针
p1->next = 0;
//这里不能给P2赋值
//p1为链表新节点,P2为链表尾节点,
//p2 = p1;
printf("输入学号\n");
scanf("%d",&p1->num);
printf("输入成绩\n");
scanf("%f",&p1->score);
if(p1->num != 0)
{
n = n+1;
if(n == 1 )
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
}
}while (p1->num != 0);
p2->next = NULL;
returnhead;
}
xieglt 发表于 2020-11-18 09:04
建立链表的函数有问题
感谢老哥。我马虎了!!!!!
页:
[1]