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

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

/**
     * 对两个有序链表进行有序合并
     * 
     * @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