Check if two linked lists merge. If so, where?

后端 未结 26 1397
陌清茗
陌清茗 2020-12-07 06:43

This question may be old, but I couldn\'t think of an answer.

Say, there are two lists of different lengths, merging at a point; how do we know wher

26条回答
  •  庸人自扰
    2020-12-07 07:38

    A O(n) complexity solution. But based on an assumption.

    assumption is: both nodes are having only positive integers.

    logic : make all the integer of list1 to negative. Then walk through the list2, till you get a negative integer. Once found => take it, change the sign back to positive and return.

    static int findMergeNode(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
    
        SinglyLinkedListNode current = head1; //head1 is give to be not null.
    
        //mark all head1 nodes as negative
        while(true){
            current.data = -current.data;
            current = current.next;
            if(current==null) break;
        }
    
        current=head2; //given as not null
        while(true){
            if(current.data<0) return -current.data;
            current = current.next;
        }
    
    }
    

提交回复
热议问题