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

后端 未结 26 1384
陌清茗
陌清茗 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:17

    You can add the nodes of list1 to a hashset and the loop through the second and if any node of list2 is already present in the set .If yes, then thats the merge node

    static int findMergeNode(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
        HashSet set=new HashSet();
        while(head1!=null)
        {
            set.add(head1);
            head1=head1.next;
        }
        while(head2!=null){
            if(set.contains(head2){
                return head2.data;
            }
        }
        return -1;
    }
    

提交回复
热议问题