1.代码一
思想:在main函数中实行三次头插法,在insertFromHead()函数中,主要创建新的节点new,开辟空间,输入想要增加的data;根据头节点的情况来判断插入,
如果head == NULL;head = new; 返回头节点 ;
如果不为空,新节点 new -> next = head; head = new ;返回头节点
#include<stdio.h>
#include<stdlib.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
struct Test *point;
point = head;
printf("output the new insert data:\n");
while(point !=NULL){
printf("%d ",point->data);
point = point->next;
}
putchar('\n');
}
struct Test* insertFromHead(struct Test *head)
{
struct Test *new;
new = (struct Test*)malloc(sizeof(struct Test));
printf("Please input your new node data:\n");
scanf("%d",&(new->data));
if(head ==NULL)
{
head = new;
return head;
}else
{
new ->next = head;
head = new;
}
return head;
}
int main()
{
int i = 3;
struct Test *head = NULL;
while(i--){
head = insertFromHead(head);
}
printLink(head);
return 0;
}
2.代码二
优化思想:
在insertFromHead()函数,用while(1)无限循环 输入, 当输入的data =0 时;终止输入,返回 head ,打印函数。
#include<stdio.h>
#include<stdlib.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
struct Test *point;
point = head;
printf("output the new insert data:\n");
while(point !=NULL){
printf("%d ",point->data);
point = point->next;
}
putchar('\n');
}
struct Test* insertFromHead(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test*)malloc(sizeof(struct Test));
printf("Please 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;
}
int main()
{
struct Test *head = NULL;
head = insertFromHead(head);
printLink(head);
return 0;
}
3.代码三
优化思想:创建链表和插入节点的两个功能用函数封装的方式分开,目的是有利于调用插入函数;
insertFromHead() 函数中,判断head是否为空,否则插入
creatLinkHead() 函数中,开辟new 节点的空间,在while(1)循环中,无限输入data,若data为0则跳出循环,不为0则调用插入函数insertFromHead()
另外,在动态创建链表的同时,''new'' ,可以用free()函数释放内存。
#include<stdio.h>
#include<stdlib.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
struct Test *point;
point = head;
printf("output the new insert data:\n");
while(point !=NULL){
printf("%d ",point->data);
point = point->next;
}
putchar('\n');
}
struct Test* insertFromHead(struct Test *head,struct Test *new)
{
if(head ==NULL)
{
head = new;
}else
{
new ->next = head;
head = new;
}
return head;
}
struct Test *creatLink(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test*)malloc(sizeof(struct Test));
printf("Please 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);
}
}
int main()
{
struct Test *head = NULL;
struct Test t1 = {1000,NULL};
head = creatLink(head);
printLink(head);
head = insertFromHead(head,&t1);
printLink(head);
return 0;
}