Find Merge Point of Two Lists


Problem Statement :


This challenge is part of a tutorial track by MyCodeSchool

Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share a common node, return that node's data  value.

Note: After the merge point, both lists will share the same node pointers.

Example

In the diagram below, the two lists converge at Node x:

[List #1] a--->b--->c
                     \
                      x--->y--->z--->NULL
                     /
     [List #2] p--->q
Function Description

Complete the findMergeNode function in the editor below.

findMergeNode has the following parameters:

SinglyLinkedListNode pointer head1: a reference to the head of the first list
SinglyLinkedListNode pointer head2: a reference to the head of the second list

Returns

int: the data value of the node where the lists merge


Input Format

Do not read any input from stdin/console.

The first line contains an integer t, the number of test cases.



Solution :



title-img


                            Solution in C :

In C++ :

/*
   Find merge point of two linked lists
   Node is defined as
   struct Node
   {
       int data;
       Node* next;
   }
*/
int getCount(Node* head)
{
  Node* current = head;
  int count = 0;
 
  while (current != NULL)
  {
    count++;
    current = current->next;
  }
 
  return count;
}

int getNode(int d, Node* head1, Node* head2)
{
  int i;
  Node* current1 = head1;
  Node* current2 = head2;
 
  for(i = 0; i < d; i++)
  {
    if(current1 == NULL)
    {  return -1; }
    current1 = current1->next;
  }
 
  while(current1 !=  NULL && current2 != NULL)
  {
    if(current1 == current2)
      return current1->data;
    current1= current1->next;
    current2= current2->next;
  }
 
  return -1;
}

int FindMergeNode(Node *headA, Node *headB)
{
    // Complete this function
    // Do not write the main method. 
    int c1 = getCount(headA);
  int c2 = getCount(headB);
  int d;
 
  if(c1 > c2)
  {
    d = c1 - c2;
    return getNode(d, headA, headB);
  }
  else
  {
    d = c2 - c1;
    return getNode(d, headB, headA);
  }
}




In Java : 



/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/
int FindMergeNode(Node headA, Node headB) {
    // Complete this function
    // Do not write the main method. 
      
    int countA=0;
    int countB=0;
    
    Node tempA=headA;
    Node tempB=headB;

    while(tempA!=null)
        {
        countA++;
        tempA=tempA.next;
    }
    
    
    while(tempB!=null)
        {
        countB++;
        tempB=tempB.next;
    }
    int diff=0;
    if(countA>countB)
        diff=countA-countB;
    else
        diff=countB-countA;
    tempA=headA;
    tempB=headB;
    if(countA>countB)
        {
         while(diff >0)
         {tempA=tempA.next;
         diff--;}
        
    }
    else
        {while(diff >0)
        { tempB=tempB.next;
          diff--;}
        
        
        }
    
    while(tempA!=null && tempB!=null)
    {
        
        tempA=tempA.next;
        tempB=tempB.next;
        if(tempA==tempB)
            return tempA.data;
        
    }
    return 0;
    

}



In python3 :



"""
 Find the node at which both lists merge and return the data of that node.
 head could be None as well for empty list
 Node is defined as
 
 class Node(object):
 
   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 
"""

def FindMergeNode(a, b):
    h = {}
    while a != None:
        h[a.data] = a.data
        a = a.next
    while b != None:
        if b.data in h:
            return h[b.data]
        b = b.next
    return None
  
  
  
  
  
  In C :


// Complete the findMergeNode function below.

/*
 * For your reference:
 *
 * SinglyLinkedListNode {
 *     int data;
 *     SinglyLinkedListNode* next;
 * };
 *
 */
#include <math.h>
int findMergeNode(SinglyLinkedListNode *headA, SinglyLinkedListNode *headB)
{
    // Complete this function
    // Do not write the main method. 
    int countA = 0;
    int countB = 0;
    struct SinglyLinkedListNode *tempHeadA, *tempHeadB;
    tempHeadA = headA;
    tempHeadB = headB;
    
    while(tempHeadA != NULL){
        countA++;
        tempHeadA = tempHeadA->next;
    }
    while(tempHeadB != NULL){
        countB++;
        tempHeadB = tempHeadB->next;
    }
    
    // printf("%d %d", countA,countB);
    int biggerNodeExtraNodes = abs(countA - countB);
    // printf("%d", biggerNodeExtraNodes);
    while(biggerNodeExtraNodes--){
         printf("33333333333");
        if(countA > countB){
            headA = headA->next;
        } else{
             headB = headB->next;
        }
    }
    while(headA != NULL){
        printf("asdfghjklpoiuytredxdcfgh");
        if(headA == headB){
            return headA->data;
        }else{
             headA = headA->next;
             headB = headB->next;
        }
    }
    return 1;
}
                        








View More Similar Problems

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →