Linear data structures Case 4 - ordered after the merger of the two single-chain consolidation remains orderly

I. INTRODUCTION

EMSP; then we define a new chain, the two elements of the list sequentially comparison, comparing the smallest to the front into the new list.

Second, the code

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

Guess you like

Origin www.cnblogs.com/gary97/p/12289633.html