链表--有序链表的合并C语言实现

合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。

#include <stdio.h>
#include <stdlib.h>

typedef int data_t;
typedef struct ListNode{
    data_t val;
    struct ListNode *next;
}node_t;

node_t *merge(node_t *phead1, node_t *phead2){



    node_t *cur = (node_t *) malloc(sizeof(node_t));
    cur->next = NULL;
    node_t *res = cur;

    if(phead1->next == NULL){
        cur = phead2;
        return cur;
    }
    if(phead2->next == NULL){
        cur = phead1;
        return cur;
    }

    phead1 = phead1->next;
    phead2 = phead2->next;

    while (phead1 != NULL && phead2 != NULL){
        if(phead1->val <= phead2->val){
            cur->next = phead1;
            cur = cur->next;
            phead1 = phead1->next;
        } else{
            cur->next = phead2;
            cur = cur->next;
            phead2 = phead2->next;
        }
    }
    if(phead1 != NULL){
        cur->next = phead1;
    }
    if(phead2 != NULL){
        cur->next = phead2;
    }

    return res;
}

node_t *merge_list(node_t **list, int num){
    for (int i = 1; i < num; ++i) {
        list[0] = merge(list[0], list[i]);
    }
    return list[0];
}

//节点插入
void node_insert(struct ListNode* head, data_t x){

    struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode));
    node->val = x;
    while (head->next != NULL){
        head = head->next;
    }

    node->next = head->next;
    head->next = node;

}
/**
 * 递增链表创建
 * @param start 起始大小
 * @param num 链表长度
 * @return
 */
struct ListNode* list_create(int start, int num){
    struct ListNode* list = (struct ListNode*) malloc(sizeof(struct ListNode));
    list->next = NULL;

    for (int i = 0; i < num; ++i) {
        node_insert(list,i+start);
    }

    return list;
}

int main(){

    node_t *list1 = list_create(1,2);
    node_t *list2 = list_create(2,0);
    node_t *list3 = list_create(1,1);
    node_t *list4 = list_create(5,4);

    node_t *list[4] = {list1,list2,list3,list4};

    node_t *res = merge_list(list,4);

    while (res->next != NULL){
        printf("%d ",res->next->val);
        res = res->next;
    }
    printf("\n");


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值