首页 > 代码库 > 链表(14)----合并两个有序链表

链表(14)----合并两个有序链表

1、链表定义

typedef struct ListElement_t_ {
    void *data;
    struct ListElement_t_ *next;
} ListElement_t;




typedef struct List_t_{
    int size;
    int capacity;
    ListElement_t *head;
    ListElement_t *tail;
} List_t;

2、合并两个有序链表


ListElement_t * MergeList( ListElement_t *pHead1, ListElement_t *pHead2, int( *compare)(const void *key1, const void *key2)){
    if(  compare == NULL )
        return NULL;
    if( pHead1 == NULL)
        return pHead2;
    if( pHead2 == NULL )
        return pHead1;

    ListElement_t *pMergeHead = NULL;
    if( compare(pHead1->data, pHead2->data ) > 0 ) {
        pMergeHead = pHead1;
        pHead1 = pHead1->next;
    } else {
        pMergeHead = pHead2;
        pHead2 = pHead2->next;
    }

    ListElement_t *pNode = pMergeHead;
    while( pHead1 != NULL && pHead2 != NULL ){
        if( compare( pHead1->data, pHead2->data ) > 0 ){
             pNode->next = pHead1;
            pHead1 = pHead1->next;
        } else {
            pNode->next = pHead2;
            pHead2 = pHead2->next;
        }
         pNode = pNode->next;
         pNode->next = NULL;
    }

    if( pHead1 != NULL ){
        pNode->next = pHead1;
    } else if( pHead2 != NULL ){
        pNode->next = pHead2
    }   

    return pMergeHead;
}


链表(14)----合并两个有序链表