数据结构和算法之单向链表三:合并两个有序链表

  我们以前在介绍排序算法的时候介绍过一种排序算法叫做归并排序,我们现在需要思考一个问题,能不能利用归并的思想对两个有序的单向链表进行合并。

/**
     * 对两个有序链表进行有序合并
     * 
     * @param head1
     * @param head2
     * @return
     */
    public Node mergeList(Node head1, Node head2) {
        // 判断链表是否有为空的情况
        if (head1 == null && head2 == null) {
            return null;
        }
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        // 定义两个节点
        Node first = null;
        Node current = null;
        // 选取头结点
        if (head1.date > head2.date) {
            first = head2;
            current = first;
            head2 = head2.next;
        } else {
            first = head1;
            current = head1;
            head1 = head1.next;
        }
        // 对两个链表进行合并
        while (head1 != null && head2 != null) {
            if (head1.date < head2.date) {
                current.next = head1;
                current = current.next;
                head1 = head1.next;
            } else {
                current.next = head2;
                current = current.next;
                head2 = head2.next;
            }
        }
        // 对剩下的节点进行合并
        while (head1 != null) {
            current.next = head1;
            head1 = head1.next;
            current = current.next;
        }
        while (head2 != null) {
            current.next = head2;
            head2 = head2.next;
            current = current.next;
        }
        return first;
    }

  请把这个方法放在单向链表的第一篇基础方法里面进行测试即可,我们通过代码可以很清楚的观察到通篇利用的就是归并的思想,对于两个有序链表的整合。但是我们在这里需要提出注意的是,对于空指针这一项的控制,也就是对于链表为空的控制,这时链表进行操作时比较忌讳的问题。一定要提前对链表是否为空,或者对应节点是否为空进行应该有的判断。

转载于:https://www.cnblogs.com/zslli/p/7995435.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值