动态创建链表
创建链表分为两大方法:第一个是头部插入法,简称头插法;第二个是尾部插入法,简称尾插法。
头插法
头插法:每次将新插入的元素放在链表首
结点的结构体定义
typedef struct LNode{
int data;
struct LNode *next;
}LNode,LinkList;
头插法函数
LinkList *list_HeadInsert(LinkList *L)
{
LNode *s;
int x;
int i=1;
L=(LinkList *)malloc(sizeof(LNode));
L->next = NULL;
printf("please input %d num\n",i);
scanf("%d",&(x));
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
i++;
printf("please input %d num\n",i);
scanf("%d",&x);
}
return L;
}
主函数
int main()
{
int i;
LinkList *L=NULL;
L=list_HeadInsert(L);
LNode *p=L->next;
while(p!=NULL){
printf("%d\n",p->data);
p=p->next;
}
}
尾插法
尾插法:每次将新插入的元素放在链表尾
结点的结构体定义
typedef struct LNode{
int data;
struct LNode *next;
}LNode,LinkList;
尾插法函数
LinkList *list_TailInsert(LinkList *L)
{
int x;
int i=1;
L=(LinkList *)malloc(sizeof(LNode));
L->next = NULL;
LNode *s;
LNode *r=L;
printf("please input %d num\n",i);
scanf("%d",&(x));
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
i++;
printf("please input %d num\n",i);
scanf("%d",&x);
}
s->next=NULL;
return L;
}
主函数
int main()
{
int i;
LinkList *L=NULL;
L=list_TailInsert(L);
LNode *p=L->next;
while(p!=NULL){
printf("%d\n",p->data);
p=p->next;
}
}