写了一个动态链表的建立和删除函数,执行删除函数只能删除有的元素,删除没有的元素,希望程序打印“没有找到节点”,但是一输入数据就返回3221225725
代码如下
#include<stdio.h>
#include<malloc.h>
struct Student {
int num;
int score;
struct Student* next;
};
int n;
struct Student* a()
{
struct Student* head, * p1, * p2;
n = 0;
p1 = p2 = (struct Student*)malloc(sizeof(struct Student));
printf("请输入第%d位的成绩:",n+1);
scanf("%d%d", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0)
{
n = n + 1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
p1 = (struct Student*)malloc(sizeof(struct Student));
printf("请输入第%d位的成绩:", n + 1);
scanf("%d%d", &p1->num, &p1->score);
p2->next = NULL;
}
return head;
}
struct Student* b(struct Student* head)
{
int b;
struct Student * p1, *p2;
p1=head;
p2=NULL;
printf("请输入删除的学生学号;");
scanf("%d",&b);
while(p1->num != b&&p1!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1==NULL)
{
printf("找不到节点\n");
}
else
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
free(p1);
}
return(head);
}
int main()
{
struct Student* pt;
pt = a();
pt=b(pt);
while (pt)
{
printf("%d %d\n", pt->num, pt->score);
pt = pt->next;
}
return 0;
}
程序执行
}
while(p1->num != b&&p1!=NULL)
p1!=NULL
这句话要放在前面判断,不然p1等于NULL的时候就会导致空指针访问了。while(p1!=NULL&&p1->num != b)
应该先判断p1 != NULL在访问p1->num != b,否则p1==NULL的时候,对NULL调用num直接炸了
#include <stdio.h>
#include <malloc.h>
struct Student
{
int num;
int score;
struct Student *next;
};
int n;
struct Student *a()
{
struct Student *head, *p1, *p2;
n = 0;
p1 = p2 = (struct Student *)malloc(sizeof(struct Student));
printf("请输入第%d位的成绩:", n + 1);
scanf("%d%d", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0)
{
n = n + 1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
p1 = (struct Student *)malloc(sizeof(struct Student));
printf("请输入第%d位的成绩:", n + 1);
scanf("%d%d", &p1->num, &p1->score);
p2->next = NULL;
}
return head;
}
struct Student *b(struct Student *head)
{
int b;
int flag = 1;
struct Student *p2;
p2 = (struct Student *)malloc(sizeof(struct Student));
p2->next = head;
printf("请输入删除的学生学号;");
scanf("%d", &b);
while (p2->next != NULL)
{
if (p2->next->num == b)
{
p2->next = p2->next->next;
flag = 0;
break;
}
p2 = p2->next;
}
if (flag)
{
printf("找不到节点\n");
}
return (p2->next);
}
int main()
{
struct Student *pt;
pt = a();
pt = b(pt);
while (pt)
{
printf("%d %d\n", pt->num, pt->score);
pt = pt->next;
}
return 0;
}