zoukankan      html  css  js  c++  java
  • 【单链表】头插法 & 尾插法

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

    【尾插法】

    返回:链表头节点指针

    //尾插法
    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;
    }
  • 相关阅读:
    POJ 2411 Mondriaan's Dream -- 状压DP
    codeforces 792A-D
    codeforces 796A-D
    Acdream1201 SuSu's Power
    HDU 2818 Building Block
    C# NetStream
    基于Duff's Device的C简易无栈协程实现
    CentOS 多版本 GCC 共存
    2017杭电多校第一场
    2019杭电多校第十场
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/14053137.html
Copyright © 2011-2022 走看看