链表必学算法(三):归并法


/*归并法:用于合并两个链表*/

/*
 * SCs in different cases
 * author: Whywait
 */

typedef struct node {
    Elemtype     data;
    struct node* next;
} Lnode;

/*case ONE*/

Lnode* merge1(Linklist& LA, Linklist& LB) {
    // merge two sorted Singly linked lists
    // LA, LB and the return one ( LC ) all have a head node
    // all the linklist are sorted in the same way: increasing or decreasing
    // we assume that all the slists are sorted in an increasing order
    // KEY: insert in the tail

    Lnode* LC = (Lnode*)malloc(sizeof(Lnode));
    LC->next  = NULL;
    Lnode *pa = LA->next, *pb = LB->next, *pc = LC;

    while (pa && pb) {
        if (pa->data < pb->data) {
            pc->next = pa;
            pa       = pa->next;
        } else {
            pc->next = pb;
            pb       = pb->next;
        }
        pc = pc->next;
    }

    if (pa)
        pc->next = pa;
    if (pb)
        pc->next = pb;
    return LC;
}

/*case TWO*/

Lnode* merge2(Linklist& LA, Linklist& LB) {
    // merge two sorted Singly linked lists
    // LA, LB and the return one ( LC ) all have a head node
    // all the linklist are sorted not in the same way:
    //		LA and LB are the same, but LC just the other way
    // we assume that LA and LB are sorted in an increasing order
    // KEY: insert in the front

    Lnode* LC = (Lnode*)malloc(sizeof(Lnode));
    LC->next  = NULL;
    Lnode *pa = LA->next, *pb = LB->next, *temp = NULL;

    while (pa && pb) {
        if (pa->data < pb->data) {
            temp     = pa->next;
            pa->next = LC->next;
            LC->next = pa;
            pa       = temp;
        } else {
            temp     = pb->next;
            pb->next = LC->next;
            LC->next = pb;
            pb       = temp;
        }
    }

    // only one of the following "while" will be excuted
    while (pa) {
        temp     = pa->next;
        pa->next = LC->next;
        LC->next = pa;
        pa       = temp;
    }
    while (pb) {
        temp     = pb->next;
        pb->next = LC->next;
        LC->next = pb;
        pb       = temp;
    }

    return LC;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AuthurLEE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值