-
Notifications
You must be signed in to change notification settings - Fork 66
/
checkingAndDeletingLoopInLinkedList.c
82 lines (69 loc) · 1.47 KB
/
checkingAndDeletingLoopInLinkedList.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void disp(struct node *q) {
struct node *p = q;
while (p) {
printf("%d\n", p->data);
p = p->next;
}
}
struct node *checkReturnLoop(struct node *head) {
struct node *p, *q;
p = q = head;
while (p && q) {
q = q->next;
if (p) {
q = q->next;
}
p = p->next;
if (p == q) {
return p;
}
}
return NULL;
}
struct node *detect(struct node *head) {
struct node *t = checkReturnLoop(head);
if (t == NULL) {
printf("loop not detected");
return NULL;
} else {
struct node *p = head;
while (p != t) {
p = p->next;
t = t->next;
}
return p;
}
}
void breakLoop(struct node *head) {
struct node *t = checkReturnLoop(head);
struct node *p = t;
while (p->next != t) {
p = p->next;
}
t->next = NULL;
disp(head);
}
int main() {
struct node *first = (struct node *)malloc(sizeof(struct node));
struct node *second = (struct node *)malloc(sizeof(struct node));
struct node *third = (struct node *)malloc(sizeof(struct node));
struct node *fourth = (struct node *)malloc(sizeof(struct node));
first->data = 1;
first->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = second;
int x = detect(first)->data;
printf("the starting node of the loop in the linked list is %d\n", x);
breakLoop(first);
return 0;
}