linked list distance between two nodes

Solutions on MaxInterview for linked list distance between two nodes by the best coders in the world

showing results for - "linked list distance between two nodes"
Roberta
07 Jan 2018
1typedef struct node {
2    int data;
3    struct node *next;
4} nodal;
5
6nodal *distance(nodal *start) {
7    int n1, n2, d1 = 0, d2 = 0, length = 0;
8    if (start == NULL) {
9        printf("List is empty\n");
10    } else {
11        printf("\nEnter the fist node element : ");
12        if (scanf("%d", &n1) != 1) {
13            printf("invalid input\n");
14            return start;
15        }
16        printf("\nEnter the second node element : ");
17        if (scanf("%d", &n2) != 1) {
18            printf("invalid input\n");
19            return start;
20        }
21        nodal *ptr = start;
22        for (;;) {
23            length++;
24            if (ptr->data == n1 && !d1) {
25                d1 = length;
26            } else if (ptr->data == n2) {
27                if (d1) {
28                    d2 = length;
29                    break;
30                }
31                if (!d2)
32                    d2 = length;
33            }
34            ptr = ptr->next;
35            if (ptr == start)
36                break;
37        }
38    }
39    if (d1 && d2) {
40        int dist = d2 - d1;
41        if (dist < 0)
42            dist += length;
43        printf("The distance between node(%d) and node(%d) is %d\n", d1, d2, dist);
44    } else {
45        if (d2)
46            printf("node(%d) not found\n", d1);
47        if (d1)
48            printf("node(%d) not found\n", d2);
49    }
50    return start;
51}
52
similar questions
queries leading to this page
linked list distance between two nodes