C语言中单向链表头结点问题

来源:百度知道 编辑:UC知道 时间:2024/05/16 09:37:43
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct student)
struct student
{
int num;
struct student *next;
};
int n;
struct student *creat()
{
struct student *head,*p1,*p2;
n=0;head=NULL;
p1=p2=(struct student *)malloc(LEN);
scanf("%d",&p1->num);
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d",&p1->num);
}
p2->next=NULL;
return(head);
}
void print(struct student *head)
{
struct student *p;
printf("\nNow,these %d records are:\n",n);
p=head;
while(p!=NULL)
{
printf("%6d\n",p->num);
p=p->next;
}
}
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head=

head=del(head,1);//main()函数里,这句应是这样。没给head赋值,del函数不能改变他的值,你改变的只是del函数里的副本 head 的值。

另一做法,可以帮助你理解:

struct student *del(struct student **head,int num)//del函数改成这样
{
struct student *p1,*p2;
if(*head==NULL) {printf("\nList null!\n");goto end;}
p1=*head;
while(num!=p1->num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}
if(num==p1->num)
{
if(p1==*head) *head=p1->next;
else p2->next=p1->next;
printf("delete:%d\n",num);
n=n-1;
}
else printf("%d not been found!\n",num);
end:;
return(*head);
}
del(&head,1);//主函数里的调用,参数为&head(取head指针变量的地址)

我大致的看了一下你的程序 首先你定义了struct结构体 在以后调用的时候就可以不用再写struct student了 直接写student就行
然后我发现有这么一句
while(num!=p1->num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}
也就是说如果我输入三个2的话就什么操作都不执行在输出一遍整个链表是不?
实在看不懂那一块是干嘛的。。。。
另外 用malloc申请了内存一定记得delete 不然会造成内存泄露