链表的动态插入有两种方法:头插法和尾插法
1、头插法
头插法相当于栈,都是先进后出,最后一个进的元素就是链表的头结点。
新插入的元素的下一个地址指向原来的链表头.
struct test *inputNumber(struct test *head)
{
struct test *new;
new=(struct test *)malloc(sizeof(struct test)); //开辟空间
new->next=NULL; //避免成为野指针;
printf("请输入数据:");
scanf("%d",&(new->data));
if(head==NULL)
{
head=new;
return head;
}else{
new->next=head;
head=new;
}
return head;
}
优化版本:拆开成两个函数,insertHead函数方便后续插入数据.
struct link *insertHead(struct link *head,struct link *new)
{
if(head==NULL)
{
head=new;
}
else
{
new->next=head;
head=new;
}
return head;
}
struct link *createLink(struct link *head)
{
struct link *new;
while(1)
{
new=(struct link *)malloc(sizeof(struct link));
new->next=NULL;
printf("请输入数据:");
scanf("%d",&(new->data));
if(new->data==0)
{
printf("输入为0停止插入数据\n");
free(new);
return head;
}
head=insertHead(head,new);
}
}
eg:输入1,2,3,4,5
则输出为5,4,3,2,1
2、尾插法
struct link *insertBehind(struct link *head,struct link *new)
{
struct link *p=head;
if(p==NULL)
{
head=new; //本身为空
return head;
}
while(head->next != NULL)
{
p=p->next; //若不为NULL,则一直移动至为NULL为止;
}
p->next = new; //此时指向尾部.
return head;
}