1)头插法:新节点作为头。
代码:
struct Test *createFromHead(struct Test*head)
{ struct Test *new;
new=(struct Test*)malloc(sizeof(struct Test));//malloc为分配指针,在删除该节点时需要释放内存
printf("input your new data:\n");
scanf("%d",&(new->data));
if(head==NULL){
head=new;
return head; //头指针为空时,即输入第一个数据时。
}else{
new->next=head;
head=new;
}
return head;
}//要创建多少个在main函数用while循环确定。
2)尾插法:从尾部插入。
代码:
struct Test *insertBehind(struct Test *head,struct Test *new){
struct Test *p=head;
if(p==NULL){
head=new;
return head;
}//在没有数据时
while(p->next!=NULL){
p=p->next;
}//此时p指向尾巴
p->next=new;
return head;
}//要创建多少个在main函数用while循环确定。