Search code examples
cdata-structureslinked-listcircular-list

Distance between two nodes in circular linked list


I want to find the distance between two nodes (number of node between them) in a circular linked list.

Where nodal is :

typedef struct node
{
    int data;
    struct node *next;
}nodal;

nodal *distance(nodal *start)
{
    int n1,n2,d1=0,d2=0,c=0;
    if(start==NULL)
    {
        printf("\nList is empty");
    }
    else
    {
        printf("\nEnter the fist node element : ");
        scanf("%d",&n1);
        printf("\nEnter the second node element : ");
        scanf("%d",&n2);
        nodal *ptr=start;
        while(ptr->next!=start)
        {
            c++;
            if(ptr->data==n1)
            {
                d1=c;
            }
            if(ptr->data==n2)
            {
                d2=c;
            }
        }
    }
    printf("The distance between two nodes is %d",(d2-d1));
    return start;
}

I doesn't give any output.

Also suppose if circular list contains following data :

1,2,3,4,5,6,7,8,9

And if I give input

First node element as 9

Second node element as 4

Then this algorithm won't work. Any suggestions for the change ?


Solution

  • Start counting when you find the first node and stop when you find the second one, something like:

    int inc = 0, dist = 0;
    
    if (n1 == n2) {
        return 0;
    }
    node = start;
    while (node) {
        dist += inc;
        if ((node->data == n1) || (node->data == n2)) {
            if (inc++ == 1) return dist;
        }
        node = node->next;
        if (node == start) break;
    }
    return 0;