公共代码块
#include <stdio.h>
#include <stdlib.h>
struct Test{
int num;
struct Test *next;
}; //创建结构体
void listLink(struct Test *head)
{
while(head!=NULL)
{
printf("%d ",head->num);
head=head->next;
}
putchar('\n');
} //列出结构体中的数据的函数
头插法创建添加动态链表
/*insert head 头插法*/
struct Test *insertHead(struct Test *head,struct Test *new)
{
if(head==NULL) //头节点都没有,那新的就是头节点
{
head=new;
return head;
}
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));
new->next=NULL;
printf("Please input num:");
scanf("%d",&(new->num));
if(new->num ==0)
{
printf("Quit!\n");
free(new);
return head;
}else{
head = insertHead(head,new);
}
}
}
int main()
{
struct Test *head = NULL; //初始化头节点
head = createLink(head); //使用头插法创建链表
listLink(head); //列出链表所有的数据
return 0;
}
运行结果
尾插法创建添加动态链表
/*insert tail*/
struct Test *inserttail(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->next = new;//链表尾指向新节点
return head; //没有改变头节点,所以返回head就行了
}
struct Test *createLink(struct Test *head)//以尾插法方式创建链表
{
struct Test *new;
while(1){
new = (struct Test*)malloc(sizeof(struct Test));
new->next=NULL;
printf("Please input num:");
scanf("%d",&(new->num));
if(new->num ==0)
{
printf("Quit!\n");
free(new);
return head;
}else{
head = inserttail(head,new);
}
}
}
运行结果
当然你想手动添加也是行的!
int main()
{
struct Test *head = NULL;
head = createLink(head);
listLink(head);
struct Test t1={88,NULL};
head = inserttail(head,&t1);
listLink(head);
return 0;
}