用头插法和尾插法创建单链表

用头插法创建单链表

//还是尾插法用的比较多
头插法

#include<stdio.h>
#include<stdlib.h>
int main()
{
    struct la
   {
        int a;
        struct la *next;
   }*head,*p;
    head=malloc(sizeof(struct la));//分配地址
    head->next=NULL; 
 while(1)
    {
        p=malloc(sizeof(struct la));
        scanf("%d",&p->a);
        if(!p->a)//如果这个数是0,break;
            break;
        p->next=head->next;//不可省略 创造结点
        //输入第一个数的 p->next是NULL
        head->next=p;//head 在不停的往前退
        //输入第一个数后 head->next有了指向
    }
   int i=0;
    while(head)
    {
        if(i==0)
        {
            i=1;
            head=head->next;
        }
        printf("%d ",head->a);
        head=head->next;
    }
}

尾插法

#include<stdio.h>
#include<stdlib.h>
int main()
{
    struct la
    {
        int a;
        struct la *next;
    }*head,*p,*q,*p2;
    head=p=p2=malloc(sizeof(struct la));//分配地址
    while(1)
    {
        q=malloc(sizeof(struct la));//分配地址
        scanf("%d",&p->a);
        if(!p->a)
            break;
        p->next=q;
        p=q;
    }
    p->next=NULL;
    while(head->next)
    {
        printf("%d ",head->a);
        head=head->next;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43589396/article/details/85999657