Merge two sorted linked lists

  • + 0 comments

    Java

    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        SinglyLinkedListNode mergedHead = new SinglyLinkedListNode(0);
        SinglyLinkedListNode current = mergedHead;
    
        while (head1 != null && head2 != null) {
            if (head1.data <= head2.data) {
                current.next = head1;
                head1 = head1.next;
            } else {
                current.next = head2;
                head2 = head2.next;
            }
            current = current.next;
        }
    
        current.next = (head1 != null) ? head1 : head2;
    
        return mergedHead.next; 
    }