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

一、介绍

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;
    }
}

猜你喜欢

转载自www.cnblogs.com/gary97/p/12289633.html
今日推荐