作者:良缘喜铺-小虹 | 来源:互联网 | 2023-05-19 07:27
最近重新写链表代码时,发现又是不会写。今天重新整理下简单链表的思路。
#include
#include
typedef struct list
{
int node;
struct list *next;
}num;
int main()
{
int i,number = 0;
num *h,*c,*p;
h = NULL;
p = NULL;
printf("input your num:");
scanf("%d",&number);
for(i = 0;i {
c = (num*)malloc(sizeof(num));
if (h == NULL)
h = c;
else
p->next = c;
c->next = NULL;
printf("input the %d number:",i+1);
scanf("%d",&c->node);
//printf("the number is %d",c->node);
p = c;
}
if(h == NULL)
{
printf("there is no number!\n");
//exit(0);
}
i = 0;
c = h;
printf("the number is:\n");
while(c!=NULL)
{
i++;
printf("%d,%d\n",c->node,i);
c = c->next;
}
getchar();
return 0;
}
以上是相关代码。整体而言,先构造结构体,其中,node里可以有很多参数,比如数量,人称等等。然后就是链表构建。p的next也赋值成c,为什么呢?这位p要到了空间,
首先要确定三个链表指针,h,c,p.c分别是头,现在,尾部的节。
然后就是初始化头部。h为null,开始往链表里填数据。
通过循环的方式,最先要到动态空间,先判断是否在头部,如果不在,就将当期c的next指针初始化,然后将将p->next 赋值成c,这里我是猜测,如果不赋值,后面c将没有空间,说白了,p没有空间。如果注释掉这行,测试结果为只能存取第一节。
然后就是c的node赋值,这里c的node和next都定义完成,再将这个结构传递给p。
在读取list的时候,就不需要p了,因为c自带的指针next就可以完成上述工作。只需要检查是否为头部罢了。