码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-12-13 23:24:26      阅读:416      评论:0      收藏:0      [点我收藏+]

标签:链表

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)----合并两个有序链表

标签:链表

原文地址:http://blog.csdn.net/beitiandijun/article/details/41915243

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!