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

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

    Here is naive solution , No neeed to traverse whole lists.

    if your structured node has three fields like

    struct node {
        int data;   
        int flag;  //initially set the flag to zero  for all nodes
        struct node *next;
    };
    

    say you have two heads (head1 and head2) pointing to head of two lists.

    Traverse both the list at same pace and put the flag =1(visited flag) for that node ,

      if (node->next->field==1)//possibly longer list will have this opportunity
          //this will be your required node. 
    
    0 讨论(0)
  • 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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题