|
2鱼币
我的问题是,这个程序中有一个运行不了。就是要删除的序号不是链表中有的,然后windows就会停止运行
#include
#include
#include
#define LEN sizeof(struct student)
struct student
{
int num;
float score;
struct student *next;
};
int n;//全局变量来记录链表里的个数
void main()
{
struct student *pt, *p;
int num;
struct student *creat(void); //创建一个动态链表
void print(struct student *head);//打印链表
struct student *deletes(struct student *head, int num);//删除链表
pt = creat();
p = pt;
print(pt);
printf("要删除的序号\n");
scanf("%d", &num);
print (deletes (p , num));
}
struct student *creat(void) //定义结构体类型,返回指针值,无形参的函数
{
struct student *p1, *p2, *head;
p1 = p2 = (struct student*)malloc(LEN); //开辟一个新的结点
printf("Please enter the num :");
scanf("%d", &p1->num);
printf("Please enter the score :");
scanf("%f", &p1->score);
head = NULL;
n = 0;
while (p1 -> num)
{
n++;
if(1 == n) //注意要倒过来写
{
head = p1;
}
else
{
p2 -> next = p1; //p2 和 next 均为指针,类比二维数组,只取一次*,还是表示的地址
}
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;
}
struct student *deletes(struct student *head, int num)
{
struct student *p1, *p2;
if (head == NULL)
{
printf("\nThis list is null!!\n");
goto END;
}
p1 = head;
while (num != p1 -> num && p1 -> num != NULL)
{
p2 = p1;
p1 = p1 -> next;
}
if (num == p1 -> num)
{
if (head == p1)//删除的是头指针
{
head = p1 -> next;
}
else
{
p2 -> next = p1 -> next;
}
printf("\nDelete No: %d succeed!\n", num);
n = n-1;
}
else
{
printf("%d not been found!\n", num);//这里有问题,在删除的序号不是链表中的序号是,无法运行
}
END:
return head;
}
void print(struct student *head) //打印链表
{
struct student *p;
printf("\nThere are %d records!\n\n", n);
p = head;
if (head != NULL)
{
while(p != NULL)
{
printf("学号为%d的成绩是: %f\n", p -> num, p -> score);
p = p -> next;
}
}
}
|
最佳答案
查看完整内容
代码写错了!
while (num != p1 -> num && p1 -> num != NULL)
{
p2 = p1;
p1 = p1 -> next;
}
红色部分 应该是 p1->next 大概是你的 笔误吧!
这种问题,一般 自己 把程序跑起来,然后 局部断点调试,很容易发现的!
你的 goto 有些多了! 一般来说 正常情况下 很少使用goto的,正式的代码里面我
基本没使用过 goto,不方便 日后的阅读,和其他人的阅读,只是个人 建议,楼主怎么习惯怎么使!
|