C语言 数据结构 链表首节点的建立,该怎么处理
C语言 数据结构 链表首节点的建立
struct Student
{
char cName[20];
int iNumber;
struct Student* pNext
};
int iCount;
struct Student* Create()
{
struct Student* pHead=NULL ;
struct Student* pEnd,*pNew;
iCount=0
pEnd=pNew=(struct Student*)malloc(sizeof(struct Student));
printf("please first enter Name, then Number\n");
scanf("%s",&pNew->cName);
scanf("%d",&pNew->iNumber);
while(pNew->iNumber!=0)
{
iCount++;
if(iCount==1)
{
pNew->pNext=pHead /*使得指向为空*/
pEnd=pNew: /*跟踪新加入的节点*/
pHead=pNew; /*头指针指向首节点*/
}
else
{
pNew->pNext=NULL;
pEnd->pNext=pNew;
pEnd=pNew;
}
上面是从教材中Copy而来的。我不明白if与else之间的语句。根据教材的提示该语句是没有节点的情况下,也就是需要建立首节点儿写的语句。我不明白的地方是为什么这样写。逻辑是什么?如果用其他的语句也可以达到这样的 目标吗?或者说为什么是这三句?这三句究竟实现了那些关键点,从而达到了目标。请高手指点!
pNew=(struct Student*)rnalloc(sizeof(struct Student));
scanf("%s",&pNew->cNarne);
scanf("%d",&pNew->iNumber);
}
free(pNew);
return pHead;
}
------解决思路----------------------
楼主,自己在纸上画画图就知道了。
如果没用if里的语句,只用else里的语句,在执行到pEnd->pNext=pNew;时,pEnd为NULL,如果执行pEnd->pNext,程序就会崩溃
如果不想每次创建一个节点都判断是否为第一个节点(执行效率来说,的确有点不妥),就在前面创建一个根节点,这个根节点不存放数据,只为了标记链表的入口
------解决思路----------------------
参考代码:
https://github.com/707wk/Senior-middle-school/blob/master/Filling%20in%20the%20gaps.c
------解决思路----------------------
楼主我强烈建议你学习下语法
typedef
typedef struct Student * List;
后边凡是含有struct Student * 都可以替换成 List 极大提高易读性
struct Student
{
char cName[20];
int iNumber;
struct Student* pNext
};
int iCount;
struct Student* Create()
{
struct Student* pHead=NULL ;
struct Student* pEnd,*pNew;
iCount=0
pEnd=pNew=(struct Student*)malloc(sizeof(struct Student));
printf("please first enter Name, then Number\n");
scanf("%s",&pNew->cName);
scanf("%d",&pNew->iNumber);
while(pNew->iNumber!=0)
{
iCount++;
if(iCount==1)
{
pNew->pNext=pHead /*使得指向为空*/
pEnd=pNew: /*跟踪新加入的节点*/
pHead=pNew; /*头指针指向首节点*/
}
else
{
pNew->pNext=NULL;
pEnd->pNext=pNew;
pEnd=pNew;
}
上面是从教材中Copy而来的。我不明白if与else之间的语句。根据教材的提示该语句是没有节点的情况下,也就是需要建立首节点儿写的语句。我不明白的地方是为什么这样写。逻辑是什么?如果用其他的语句也可以达到这样的 目标吗?或者说为什么是这三句?这三句究竟实现了那些关键点,从而达到了目标。请高手指点!
pNew=(struct Student*)rnalloc(sizeof(struct Student));
scanf("%s",&pNew->cNarne);
scanf("%d",&pNew->iNumber);
}
free(pNew);
return pHead;
}
------解决思路----------------------
楼主,自己在纸上画画图就知道了。
如果没用if里的语句,只用else里的语句,在执行到pEnd->pNext=pNew;时,pEnd为NULL,如果执行pEnd->pNext,程序就会崩溃
如果不想每次创建一个节点都判断是否为第一个节点(执行效率来说,的确有点不妥),就在前面创建一个根节点,这个根节点不存放数据,只为了标记链表的入口
------解决思路----------------------
参考代码:
https://github.com/707wk/Senior-middle-school/blob/master/Filling%20in%20the%20gaps.c
------解决思路----------------------
楼主我强烈建议你学习下语法
typedef
typedef struct Student * List;
后边凡是含有struct Student * 都可以替换成 List 极大提高易读性