Merge two sorted linked lists

  • + 0 comments

    Java Solution

        static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            
            
            SinglyLinkedListNode head = new SinglyLinkedListNode(0); 
            SinglyLinkedListNode temp = head; //temp head, use for traversal
            SinglyLinkedListNode node1 = head1;
            SinglyLinkedListNode node2 = head2;
            while(node1 != null && node2 != null){
                if(node1.data < node2.data){
                    temp.next = node1;
                    node1 = node1.next;
                }else{
                    temp.next = node2;
                    node2 = node2.next;
                }
                temp = temp.next;
            }
            
            if(node1 != null){
                temp.next = node1;
            }
            
            if(node2 != null){
                temp.next = node2;
            }
            
            return head.next;
        }