头插法
从一个空表头指针开始,重复读入数据,生成新节点, 将读入数据存放到新节点的数据域中,永远是将新节点插入到当前链表的头节点的后面,第一个创建的节点是放在最后的,直到读入结束标志才停止创建。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int date;
struct Node *next;
}LNode,*Linklist;
Linklist Creat_list(Linklist head);
void Illustrate(Linklist head)
{
Linklist tem = head;
while(tem->next != NULL)
{
tem = tem->next ;
printf("%d\n",tem->date );
}
}
int main()
{
Linklist head = NULL;
printf("head=%p\n",head );
head = Creat_list(head);
Illustrate(head);
system("pause");
return 0;
}
Linklist Creat_list(Linklist head)
{
head = (Linklist)malloc(sizeof(LNode));
if(head==NULL)
{
printf("failure\n");
exit(-1);
}
printf("第一次开辟head = %p\n",head );
printf("第一次开辟head->next = %p\n",head->next );
LNode *node = NULL;
printf("初始化节点node=%p\n",node);
int count = 0;
head->next = NULL;
printf("初始化head->next = %p\n",head->next );
node = head->next ;
printf("\n");
printf("请输入节点个数:");
scanf("%d",&count);
for(int i = 0;i<count;i++)
{
node = (Linklist)malloc(sizeof(LNode));
printf("第%d个node = %p\n",i+1,node);
printf("第%d个node->next = %p\n",i+1,node->next );
node->date = i;
node->next = head->next;
head->next =node;
printf("新node->next = %p\n",node->next );
printf("新head->next = %p\n",head->next );
}
return head;
}
参考博文
自己再练习一下头插法
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE
{
int date;
struct NODE *next;
}NODE;
void Print_linklist(NODE *head);
NODE *Create_linklist(NODE *head);
int main()
{
NODE *head = NULL;
head = Create_linklist(head);
Print_linklist(head);
return 0;
}
NODE *Create_linklist(NODE *head)
{
head = (NODE*)malloc(sizeof(NODE));
if(head == NULL)
{
printf("failure\n");
exit(-1);
}
NODE *node = NULL;
head->next = NULL;
int count;
printf("请输入链表节点的个数:\n");
scanf("%d",&count);
int i;
for(i=0;i<count;i++)
{
node = (NODE*)malloc(sizeof(NODE));
node->date = i;
node->next = head->next ;
head->next = node;
}
return head;
}
void Print_linklist(NODE *head)
{
while(head->next != NULL)
{
head = head->next ;
printf("head->date = %d\n",head->date );
}
}
接下来练习一下不用for,而是用while的情况,把以上代码从int count;到整个for循环结束的这块修改为
int date;
printf("请为节点数据域输入整数date:\n");
scanf("%d",&date);
printf("当输入date为0时停止创建节点。\n");
while(date) {
node = (NODE*)malloc(sizeof(NODE));
node->date = date;
node->next = head->next ;
head->next = node;
scanf("%d",&date);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)