forked from Pavan-Kamthane/C_langauege_
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectLoop.c
75 lines (67 loc) · 1.72 KB
/
detectLoop.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
#include <stdio.h>
#include <stdlib.h>
/* A structure of linked list node */
struct node {
int data;
struct node *next;
} *head;
void initialize(){
head = NULL;
}
/*
Given a Inserts a node in front of a singly linked list.
*/
void insert(int num) {
/* Create a new Linked List node */
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = num;
/* Next pointer of new node will point to head node of linked list */
newNode->next = head;
/* make new node as new head of linked list */
head = newNode;
printf("Inserted Element : %d\n", num);
}
void findloop(struct node *head) {
struct node *slow, *fast;
slow = fast = head;
while(slow && fast && fast->next) {
/* Slow pointer will move one node per iteration whereas
fast node will move two nodes per iteration */
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
printf("Linked List contains a loop\n");
return;
}
}
printf("No Loop in Linked List\n");
}
/*
Prints a linked list from head node till tail node
*/
void printLinkedList(struct node *nodePtr) {
while (nodePtr != NULL) {
printf("%d", nodePtr->data);
nodePtr = nodePtr->next;
if(nodePtr != NULL)
printf("-->");
}
}
int main() {
initialize();
/* Creating a linked List*/
insert(8);
insert(3);
insert(2);
insert(7);
insert(9);
/* Create loop in linked list. Set next pointer of last node to second node from head */
head->next->next->next->next->next = head->next;
findloop(head);
return 0;
}
Output
Inserted Element : 8
Inserted Element : 3
Inserted Element : 2
Inserted El