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

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

    this solution iterates each list only once...no modification of list required too..though you may complain about space..
    1) Basically you iterate in list1 and store the address of each node in an array(which stores unsigned int value)
    2) Then you iterate list2, and for each node's address ---> you search through the array that you find a match or not...if you do then this is the merging node

    //pseudocode
    //for the first list
    p1=list1;
    unsigned int addr[];//to store addresses
    i=0;
    while(p1!=null){
      addr[i]=&p1;
      p1=p1->next;
    }
    int len=sizeof(addr)/sizeof(int);//calculates length of array addr
    //for the second list
    p2=list2;
    while(p2!=null){
      if(search(addr[],len,&p2)==1)//match found
      {
        //this is the merging node
        return (p2);
      }
      p2=p2->next;
    }
    
    int search(addr,len,p2){
      i=0;  
      while(i

    Hope it is a valid solution...

提交回复
热议问题