小甲鱼的练习题,为什么不能转换print(del(p,n));
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)//student结构的大小
struct student *creat();//创建链表
struct stduent *del(struct student *head,int num);//del函数用于删除结点,*head即链表的头指针,num是要删除的结点num
void print(struct student *head);//打印链表,可以不写括号里面的参数,参数是写给程序员看的
struct student
{
int num;
float score;
struct student *next;
};
int n;//全局变量,用来记录放了多少个数据
int main(void)
{
struct student *stu,*p;
int n;
stu=creat();
p=stu;
print( p );
printf("please enter the number to delete:");
scanf("%d",&n);
print( del(p,n) );
system("pause");
return 0;
}
struct student *creat()
{
struct student *head;
structstudent *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;
while(p1->num)
{
n++;
if(1==n)
{
head=p1;
}
else
{
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;
};
struct stduent *del(struct student *head,int num)
{
struct student *p1,*p2;
if(NULL==head)
{
printf("This list is NULL!\n\n");
goto END;
}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num=p1->num)
{
if(p1=head) //当删除的结点位于头结点时
{
head=p1->next;
}
else //一般情况
{
p2->next=p1->next;// A B C
}
printf("\nDelete the %d number succeed!\n");
n=n-1;//n作为一个全局变量,用来记录链表的数据量
}
else
{
printf("The number not been found!\n");
}
END:
return head;
};
void print(struct student *head)
{
struct student *p;
printf("There are %d records!\n\n",n);
p=head;
if(head)
{
do
{
printf("学号为%d的成绩是:%f\n",p->num,p->score);
p=p->next;
}while(p);
}
} 还没有看明白你想表达什么 这样是不行的哦, 因为del是一个删除函数, 现在你的链表里就只有一个节点, 你删除了,链表里面就没有节点了,当你用print访问的时候,访问的是已被释放的内存!
页:
[1]