不理解下面代码是如何链起来的
主要每次循环都会做last=head,那这样不就是类似太阳花那样,head为中心,数据都在外面一圈吗?
但是,遍历是正确的,那不是就是说它链起来了吗?
求解答
代码如下
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
int data;
struct _node *pRear;
}node;
int main()
{
int number;
node *head=NULL;
do{
scanf("%d",&number);
if(number!=-1){
node *p=(node*)malloc(sizeof(node));
p->data=number;
p->pRear=NULL;
node *last=head;
// printf("last.p=%p ",&last);
// printf("last.p=%p ",last);
// printf("last->pRear_p=%p ",last->pRear);
// printf("head.p=%p ",&head);
// printf("head.p=%p ",head);
if(last){
while(last->pRear!=NULL){
last=last->pRear;
}
last->pRear=p;
}else{
head=p;
}
}
}while(number!=-1);
node *ps;
for(ps=head;ps;ps=ps->pRear){
printf("%d\n",ps->data);
}
return 0;
}
last=head只是初始化last指针而已,后面if(last)会通过循环将last指针向链表后面移动,直到移动到链表尾(pRear为空),然后将last的pRear指向新的节点p,就链上啦
if(last){
while(last->pRear!=NULL){ //这里找到下一个节点为NULL的节点(就是尾结点)
last=last->pRear;
}
last->pRear=p; //将尾结点的下一个节点设为新节点
}else{
head=p; //第一次进入的时候,last=0,执行这一步,所以head能得到链表的头,后续继续输入的时候就执行if代码块,所以能连起来
}