有哪位仁兄可以花费点时间能比较清晰地解释一下这道基础的链表题目?小弟感激不尽~~~
题目:以下函数creatlist用来建立一个带头节点的单链表,链表的结果如下图所示,新的节点总是插入在链表的末尾。链表的头指针作为函数值返回,链表最后一个节点的next域放入NULL,作为链表结束标志。data为字符型数据域,next为指针域。读入时字符以#表示输入结束(#不存入链表)。
struct node
{ char data;
struct node *next;
};
struct node* creatlist()
{ struct node *h,*s,*r;char ch;
h=(struct node *)malloc(sizeof(struct node));
r=h;
ch=getchar();
while(ch!= '# ')
{ s=(struct node *)malloc(sizeof(struct node));
s-> data=ch;
r-> next=s;r=s;
ch=getchar();}
r-> next=NULL;
return h;
}
[解决办法]
h=(struct node *)malloc(sizeof(struct node)); //创建头节点
r=h; //r指向头节点 h
|
r
ch=getchar();
while(ch!= '# ')
{
s=(struct node *)malloc(sizeof(struct node)); //新建节点
s-> data=ch; //赋值
r-> next=s;r=s; //r的next节点指向s后,r指向next节点
h-> s
|
r
ch=getchar();}
r-> next=NULL;
return h;