linked list distance between two nodes
typedef struct node {
int data;
struct node *next;
} nodal;
nodal *distance(nodal *start) {
int n1, n2, d1 = 0, d2 = 0, length = 0;
if (start == NULL) {
printf("List is empty\n");
} else {
printf("\nEnter the fist node element : ");
if (scanf("%d", &n1) != 1) {
printf("invalid input\n");
return start;
}
printf("\nEnter the second node element : ");
if (scanf("%d", &n2) != 1) {
printf("invalid input\n");
return start;
}
nodal *ptr = start;
for (;;) {
length++;
if (ptr->data == n1 && !d1) {
d1 = length;
} else if (ptr->data == n2) {
if (d1) {
d2 = length;
break;
}
if (!d2)
d2 = length;
}
ptr = ptr->next;
if (ptr == start)
break;
}
}
if (d1 && d2) {
int dist = d2 - d1;
if (dist < 0)
dist += length;
printf("The distance between node(%d) and node(%d) is %d\n", d1, d2, dist);
} else {
if (d2)
printf("node(%d) not found\n", d1);
if (d1)
printf("node(%d) not found\n", d2);
}
return start;
}