线性数据结构案例4 —— 合并两个有序的单链表 合并之后依然有序

我与影子孤独终老i 提交于 2020-02-10 01:38:04

一、介绍

emsp; 我们定义一个新链表然后,将两个链表的元素依次比较,放入比较最小的放到新链表前面。

二、代码

    public static Node mergeByOrder(Node l1, Node l2) {
        if(l1.next == null || l2.next == null) {
            return l1.next == null ? l2 : l1;
        }
        Node newLinkedHead = new Node(0, "");
        l1 = l1.next; // 头节点没有数据我们不要
        l2 = l2.next; // 头节点没有数据我们不要
        Node temp = newLinkedHead;

        while (l1 != null && l2 != null) {
            if (l1.no <= l2.no) {
                temp.next = l1;
                temp = temp.next;
                l1 = l1.next;
            } else {
                temp.next = l2;
                temp = temp.next;
                l2 = l2.next;
            }
        }
        if (l1 == null) {
            temp.next= l2; // 连接剩余节点
        }
        if (l2 == null) {
            temp.next= l1; // 连接剩余节点
        }
        return newLinkedHead;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!