c语言链表的创建

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c语言链表的创建相关的知识,希望对你有一定的参考价值。

LIST *creat()

LIST *head = NULL;
LIST *prev, *current;
char index;
int node;

printf("Do you want to create how many nodes?\n");
printf("Please input node's number: ");
while(1 != scanf("%d", &node))
getchar(); //创建node的个数

for(index = 0; index < node; index++)

current = (LIST *)malloc(sizeof(LIST)); //分配新的node地址
if(head == NULL)
head = current; //空表建立的时候
else
prev->next = current; //非空表
current->next = NULL;
scanf("%d %d", ¤t->num, ¤t->age);
prev = current; //更新老node的地址

return head;

请高手解释一下例子中for循环内链表的创建过程尤其是else语句之后的!

current = (LIST *)malloc(sizeof(LIST)); //分配新的node地址
if(head == NULL) //判断head结点为空
head = current; //头结点为空,则此表为空表。
else //头结点不为空,说明此表不为空,里面有结点
prev->next = current; //先前结点的next指针指向刚分配的结点的地址。
current->next = NULL; //由于current结点当前为最后一个结点,所以要赋为NULL
scanf("%d %d", ¤t->num, ¤t->age);//这个t不知道怎么定义的
prev = current //更新结点,由于上面是prev指向current,现在我还要插入结点,肯定是在current后面插入新节点,这样current结点就变成旧结点了(不再是上面所说的刚分配的结点)所以它就要替换原来prev的位置,把prev=current;这样才可以一直循环下去。
参考技术A 这个链表做得不好。其实链表可以不用创建这一步。因为插入操作已经包含有创建功能了。else后面的语句,就如同你给绳子打结一样。链表的节点好比一段一段的绳子,现在你需要把它们都接起来。你每接一段,手就要往后移动一节,以准备给下一段打结。else后面的语句,其实就是让当前指针指向的节点后移。
我给你个程序:
#include <stdio.h>
#include <stdlib.h>

typedef struct tagPERSON //个人信息结构

char name[20];
long age;
PERSON;

//template<typename DT> //如果是C++的话,这里方便许多,可以使用模板和类
typedef struct tagLNODE* pLNODE;
typedef struct tagLNODE //链表节点

PERSON data;
pLNODE next;
LNODE;

int link_insert(pLNODE *head,PERSON data)//链表插入

pLNODE cur_tmp,lnode_tmp;

cur_tmp=*head;
lnode_tmp=(pLNODE)malloc(sizeof(LNODE));
if(lnode_tmp==NULL)return -1;
lnode_tmp->data=data;
lnode_tmp->next=NULL;

if(*head==NULL)
*head=lnode_tmp; //如果head为空,则需要对main()中的head修改,所以head的类型为指向指针的指针
else

while(cur_tmp->next!=NULL)
cur_tmp=cur_tmp->next;
cur_tmp->next=lnode_tmp;


return 0;


int link_display_cmd(pLNODE head) //控制台下的链表显示

pLNODE cur_tmp;

cur_tmp=head;
while(cur_tmp!=NULL)

printf("%s:%d\n",(cur_tmp->data).name,(cur_tmp->data).age);
cur_tmp=cur_tmp->next;

return 0;


int link_clear(pLNODE *head) //清空链表

pLNODE cur_tmp,old_tmp;

cur_tmp=*head;
while(cur_tmp!=NULL)

old_tmp=cur_tmp;
cur_tmp=cur_tmp->next;
free(old_tmp);


*head=NULL;
return 0;


int main(void)

pLNODE head=NULL;
PERSON temp;

printf("Please input the name:");
scanf("%s",temp.name);
printf("Please input the age:");
scanf("%d",&(temp.age));
while(temp.age>0)

link_insert(&head,temp);
printf("Please input the name:");
scanf("%s",temp.name);
printf("Please input the age:");
scanf("%d",&(temp.age));


link_display_cmd(head);
link_clear(&head);

return 0;

以上是关于c语言链表的创建的主要内容,如果未能解决你的问题,请参考以下文章

C语言链表的建立?

关于C语言链表的

c语言关于链表的一道题

求C语言 数据结构中的链表创建,插入和删除代码

C语言链表的问题

c语言中创建动态链表