【单链表】头插法 & 尾插法

将数组中的元素一次传递给链表中的各个结点:

【尾插法】

返回:链表头节点指针

//尾插法
struct linkNode *creat_link_list_rear(int a[], int n){

    struct linkNode *h = NULL;  //新建链表h,将每个结点依次插入到链尾,将链表的头指针返回
    struct linkNode *s;      //s指向要插入的结点
    struct linkNode *r;      //r指向链表尾结点

    for(int i=0; i<n; i++){
        s = (struct linkNode *)malloc(sizeof(struct linkNode));
        s->data = a[i];
        s->next = NULL;

        if(h == NULL){
            h = s;
        }else{
            r->next = s;
        }

        r = s;  //r指向当前链表的尾结点
    }

    return h;   //返回链表头指针
}

【头插法】

返回:链表头节点指针

//头插法
struct linkNode *creat_link_list_head(int a[], int n){
    struct linkNode *h = NULL;
    struct linkNode *s;     //s指向要插入的结点

    for(int i=5; i>=0; i--){
        s = (struct linkNode *)malloc(sizeof(struct linkNode));
        s->data = a[i];
        if(h == NULL){
            h = s;
        }else{
            s->next = h;
            h = s;
        }
    }

    return h;
}
原文地址:https://www.cnblogs.com/CPU-Easy/p/14053137.html