Merge two sorted linked lists

  • + 0 comments

    Hi, solution using Java:

    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            SinglyLinkedListNode head = new SinglyLinkedListNode(-1);
            SinglyLinkedListNode curr = head;
            
            if (head1 == null) return head2;
            if (head2 == null) return head1;
            
            while (head1 != null && head2 != null) {
                if (head1.data < head2.data) {
                    curr.next = head1;
                    head1 = head1.next;
                } else {
                    curr.next = head2;
                    head2 = head2.next;
                }
                
                curr = curr.next;
            }
            
            if (head1 == null) {
                curr.next = head2;
            } else {
                curr.next = head1;
            }
            
            return head.next;
        }