zoukankan      html  css  js  c++  java
  • C 链表合并

    
    
    #include <stdio.h>
    #include <stdlib.h>
    typedef struct node{
        int data;   //占4B
        struct node *next;  //占8B
    } List;     //共占16B

    List* creatLink(int li[], int n) {
        List *L,*curNode,*nextNode;
        L = (List*)malloc(sizeof(List));
        L->next = NULL;
        curNode = L;
        int i;
        for(i=0;i<n;i++){
            nextNode = (List*)malloc(sizeof(List));
            nextNode->data = li[i];
            nextNode->next = curNode->next;
            curNode->next = nextNode;
            curNode = nextNode;
        }
        return L;
    }
    List* mergeLink2(List *L1,List *L2){
        List *L = (List*)malloc(sizeof(List));
        List *curNode = L;
        curNode->next = L1->next;
        while(curNode->next) curNode = curNode->next;
        curNode->next = L2->next;
        return L;
        

    }
    List* mergeLink(List *L1, List *L2){
        List *L = (List*)malloc(sizeof(List));
        List *curNode = L;
        List *L1t = L1,*L2t = L2;
        L1t = L1t->next;
        L2t = L2t->next;
        while(L1t && L2t){
            if(L1t->data < L2t->data){
                curNode->next = L1t;
                curNode = L1t;
                L1t = L1t->next;
            }
            else{
                curNode->next = L2t;
                curNode = L2t;
                L2t = L2t->next;
            }
        }
        if(L1t){
            curNode->next = L1t;
        }
        else
        {
            curNode->next = L2t;
        }
        return L;
    }
    void freeLink(List **Node){
        List *temp;
        while(*Node != NULL){
            temp = *Node;
            *Node = temp->next;
            free(temp);
        }
    }
    void printLink(List *Node){
        Node = Node->next;
        while(Node != NULL){
            printf("%d   ",Node->data);
            Node= Node->next;
        }
        printf(" ");
    }
    int main(){

        int li1[6] = {1,3,5,7,9,0};
        int li2[5] = {2,4,6,8,10};
        List *L1 = creatLink(li1,sizeof(li1)/sizeof(li1[0]));
        List *L2 = creatLink(li2,sizeof(li2)/sizeof(li2[0]));
        List *L = mergeLink2(L1,L2);
        printLink(L);
        freeLink(&L1);
        freeLink(&L2);
        freeLink(&L);
        return 0;
    }
     
  • 相关阅读:
    表达式for loop
    用户输入
    字符编码
    变量字符编码
    Python安装
    Python 2 or 3?
    Python解释器
    2017中国大学生程序设计竞赛
    Educational Round 27
    Round #429 (Div.2)
  • 原文地址:https://www.cnblogs.com/Json28/p/12875176.html
Copyright © 2011-2022 走看看