Merge two sorted linked lists

  • + 0 comments

    Java 8 - Solution

    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        SinglyLinkedListNode head = null;
        SinglyLinkedListNode tail = null;
            
        while( head1!=null || head2!=null) {
            SinglyLinkedListNode t = null ;
            if ( head2 == null || (head1!=null && head1.data <= head2.data) ) {
                t = head1;
                head1 = head1.next;
            } else {
                t = head2 ;
                head2 = head2.next;                
            }
    
            if (tail != null )
                tail.next = t;
            tail = t;
            if (head == null)
                head = tail;
        }
            
        tail.next = null;
        return head;
    }