面试算法-167-合并 K 个升序链表-解

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode result = null;
        for (ListNode item : lists) {
            result = merge(result, item);
        }
        return result;
    }

    public ListNode merge(ListNode head1, ListNode head2) {
        ListNode dummy = new ListNode(0);
        ListNode p1 = dummy;
        while (head1 != null && head2 != null) {
            if (head1.val <= head2.val) {
                p1.next = head1;
                head1 = head1.next;
            } else {
                p1.next = head2;
                head2 = head2.next;
            }
            p1 = p1.next;
        }
        p1.next = head1 == null ? head2 : head1;
        return dummy.next;
    }
}
上一篇:15. 登录页案例


下一篇:工控 modbusTCP 报文