首页 > 代码库 > 链表(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)----合并两个有序链表
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。