简单的单链表问题,谢谢啦

LXW19900825 2011-02-16 05:18:11
#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *next;
};
struct node *creatlist(int a[])
{
struct node *h,*p,*q;
int i;
h=NULL;
for(i=0;i<6;i++)
{
q=(struct node*)malloc(sizeof(struct node));
q->data=a[i];
q->next=NULL;
if(h==NULL) h=p=q;
else
{
p->next=q;
p=q;
}
}
return h;
}
void outlist(struct node *h)
{
struct node *p;
p=h;
if(p==NULL)
printf("The list is NULL\n");
else
{
printf("head");
do
{
printf("->%d",p->data);
p=p->next;
}
while(p!=NULL);
printf("->end\n");
}
}
void main()
{
struct node *head;
int a[6]={2,4,10,7,5,9};
head=creatlist(a);
printf("\nThe original list :\n");
outlist(head);
}
我想问一下,在函数struct node *creatlist(int a[])中,为什么要把h赋值NULL,
还有就是在函数void outlist(struct node *h),为什么要写
if(p==NULL)
printf("The list is NULL\n");
链表不是已经生成了吗,写这个有什么作用,谢谢了


...全文
88 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
LXW19900825 2011-02-18
  • 打赏
  • 举报
回复
谢谢你了
老马何以识途 2011-02-16
  • 打赏
  • 举报
回复
h=NULL
是指针初始化,不做的话后面的
if(h==NULL)
就出问题了。
if(p==NULL)
是为了防止对空指针进行操作,因为你的链表生成部分有可能返回空链表!

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧