链表的动态创建之尾插法
用尾插法创建动态链表
C语言中创建链表需要用到结构体,所以在此之前我们先定义一个结构体。
struct test
{
int data;
struct test *next;
};
尾插法的原理就是让原本链表的next指向新创建的数据,所以我们需要写一个whlie循环,保证每次都能到达“尾巴”,让数据可以准确的在尾部插入。
while(p->next!=NULL)
{
p=p->next;
}
p->next=new;
总体代码如下
#include<stdio.h>
#include <stdlib.h>
struct test
{
int data;
struct test *next;
};
void printfLink(struct test *head)
{
struct test *p=head;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
putchar('\n');
}
struct test *createLink(struct test *head)
{
struct test *new=NULL;
while(1)
{
new=(struct test *)malloc(sizeof(struct test));
printf("请输入链表数据:");
scanf("%d",&new->data);
if(new->data==0)//输入 0 退出链表的创建
{
printf("退出链表创建\n");
return head;
}
if(head==NULL)
{
head=new;
}
else
{
struct test *p=head;
while(p->next!=NULL)//让 p 到达尾部,这样p->next=new才能准确
{
p=p->next;
}
p->next=new;
}
}
return head;
}
int main()
{
struct test *head=NULL;
head=createLink(head);//动态创建链表
printfLink(head);//遍历链表
return 0;
}