Merge two sorted linked lists

  • + 0 comments

    JS

    function mergeLists(head1, head2) {
        const list = [];
        while (head1) {
            list.push(head1.data);
            head1 = head1.next;
        }
        while (head2) {
            list.push(head2.data);
            head2 = head2.next;
        }
        list.sort((a, b) => a - b);
        const head = new SinglyLinkedListNode(list[0]);
        list.reduce((node, value, index) => {
            if (index) {
                node.next = new SinglyLinkedListNode(value);
                node = node.next;
            }
            return node;
        }, head);
        return head;
    }