头插法
(从头指针开始插入结点的插法(第一个结点为空))
#include <stdio.h>
#include <stdlib.h>
typedef struct lonlist
{
int num;
struct lonlist* next;
}Li;
typedef Li* pointlist;
pointlist creatlist()
{
pointlist head;
Li *node;
node =NULL; //(有没有好像没多大关系)
head = (pointlist)malloc(sizeof(Li));
head->next =NULL;
node =head->next; // 将最后一个节点的永远为空(头指针指向的下一个节点设为空,赋值给一个结点)
int count,i;
printf("输入数值的个数:");
scanf("%d",&count);
printf("输入数值\n");
for(i=0;i<count;i++)
{
node =(pointlist)malloc(sizeof(Li));
scanf("%d",&node->num);
node->next=head->next;
head->next=node;
}
return head;
}
void showlist(pointlist head)
{
pointlist pre;
while(head->next!=NULL)
{
pre =head;
head= head->next;
printf("%d ",head->num);
free(pre);
}
}
int main()
{
pointlist head =NULL;
head =creatlist();
showlist(head);
return 0;
}
尾插法
#include <stdio.h>
#include <stdlib.h>
typedef struct lonlist
{
int num;
struct lonlist* next;
}Li;
typedef Li* pointlist;
pointlist creatlist1()
{
pointlist head;
pointlist end;
head = (pointlist)malloc(sizeof(Li));
head->next=NULL; //初始化链表
end=head;
Li *node;
printf("输入数值的数量 :");
int count,i;
scanf("%d",&count);
printf("输入数值\n");
for(i=1;i<=count;i++)
{
node =(pointlist)malloc(sizeof(Li));
scanf("%d",&node->num);
end->next=node;
end=node;
}
end->next=NULL;
return head;
}
void showlist(pointlist head)
{
pointlist pre;
while(head->next!=NULL)
{
pre =head;
head= head->next;
printf("%d ",head->num);
free(pre);
}
}
int main()
{
pointlist head =NULL;
head =creatlist1();
showlist(head);
return 0;
}