链表的动态创建
Posted 橙子果果
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表的动态创建相关的知识,希望对你有一定的参考价值。
链表的动态创建
头插法
尾插法
struct Test* insertFromHead(struct Test* head)
struct Test *new;
while(1)
new = (struct Test *)malloc(sizeof(struct Test));
printf("input your new node data:\\n");
scanf("%d",&(new->data));
if(new->data == 0)
printf("0 quit\\n");
return head;
if(head == NULL)
head = new;
else
new->next = head;
head = new;
return head;
struct Test *head = NULL;
head = insertFromHead(head);
printLink(head);
这里是从6往前依次插入 5 4 3 2 1。
当插入0时自动结束链表的创建。
头插法优化:
struct Test* insertFromHead(struct Test* head,struct Test *new)
if(head == NULL)
head = new;
else
new->next = head;
head = new;
return head;
struct Test *createLink(struct Test *head)
struct Test *new;
while(1)
new = (struct Test *)malloc(sizeof(struct Test));
printf("input your new node data:\\n");
scanf("%d",&(new->data));
if(new->data == 0)
printf("0 quit***\\n");
free(new);
return head;
head = insertFromHead(head,new);
尾插法
struct Test* insertBehind(struct Test* head,struct Test* new)
struct Test* point=head;
if(point == NULL)
head=new;
return head;
while(point->next != NULL)
point=point->next;
point->next=new;
return head;
struct Test* creatLink2(struct Test* head)
struct Test* new;
while(1)
new=(struct Test*)malloc(sizeof(struct Test));
printf("input your new node data:\\n");
scanf("%d",&(new->data));
if(new->data == 0)
printf("0 quit***");
free(new);
return head;
head=insertBehind(head,new);
动态创建优化就是把插入单独写成一个函数。
以上是关于链表的动态创建的主要内容,如果未能解决你的问题,请参考以下文章