C语言基础-链表(二)动态创建链表、头插法、尾插法

动态创建链表

创建链表分为两大方法:第一个是头部插入法,简称头插法;第二个是尾部插入法,简称尾插法

头插法

头插法:每次将新插入的元素放在链表首

在这里插入图片描述

结点的结构体定义

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);	//头插法创建链表L
        LNode *p=L->next;	//头结点指针赋给p
        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);	//尾插法创建链表L
        LNode *p=L->next;	//头结点指针赋给p
        while(p!=NULL){
    
    		//遍历打印链表
                printf("%d\n",p->data);
                p=p->next;
        }
}

猜你喜欢

转载自blog.csdn.net/weixin_44933419/article/details/112431303
今日推荐