C语言单链表的创建
(不带头节点的)链表的创建过程大致可以分为以下几大部分:
一:前奏部分:定义出一个结构体的类型来存储节点node
struct node
{
int date;
struct node *next;
};
注意:有许多新学的人容易漏写结尾那个;
节点:节点是由所存数据和指针(下一个节点的地址)构成,建立一个结构体类型可以很好的存储这二者。
二:int main()内部部分
步骤一:利用之前定义好的结构体类型struct node写出创建过程中要用到的节点(指针形式)
struct node *head,*pnew,*pold,*t;
①头指针struct node *head
作用:指向并找到第一个节点,方便继续访问及遍历。
②循环指针struct node *pold,*pnew
pnew作用:每一次加入节点时都用pnew(记录数据,保存地址当先设为NULL)
pold的作用:①在设置完pnew的存储值以及地址为NULL以后让pold的指针域指向pnew(不是创建的第一个节点时);
②在完成 pold的指针域以后对pnew进行“pnew=pold” 操作以便循环(此时pold前移,pnew可以理解为处于一种前移且空出的状态)
③遍历指针struct node *t
t=head;
while(t!=NULL)
{
printf("%d ",t->date);
t=t->next;
}
注意:不要漏写t=head;
步骤二:用for循环创建链表
A:建立pnew指针存储新节点:先申请空间——>存储数据于节点中——>把pnew中的指针域设立为NULL
if(head==NULL)head=pnew;
else pend->next=pnew;
pend=pnew;
B为前面pold的NULL赋地址如果是第一个创立的节点就用head指向这个节点
if(head==NULL)head=pnew;
else pend->next=pnew;
pend=pnew;
C循环操作pold=pnew
此时可以理解为pold前移,pnew空出需要等下一个循环
D遍历输出
t=head;
while(t!=NULL)
{
printf("%d ",t->date);
t=t->next;
}
注意:while循环最后不用打;
整体效果
#include<stdio.h>
#include<stdlib.h>
struct node
{
int date;
struct node *next;
};
int main()
{
struct node *head,*pnew,*pold,*t;
head=NULL;
int n,a;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a);
pnew=(struct node*)malloc(sizeof(struct node));
pnew->date=a;
pnew->next=NULL;
if(head==NULL)head=pnew;
else pold->next=pnew;
pold=pnew;
}
t=head;
while(t!=NULL)
{
printf("%d ",t->date);
t=t->next;
}
return 0;
}