Loop linked list
Ngày đăng:
21/02/2022
Trả lời:
0
Lượt xem:
154
Given a Singly list, we have to find whether given linked list contains a cycle. A loop in a linked list means there is no tail node in a linked list, every node of link list is pointing to some other node of linked list. Method 1 : Fast and Slow pointer method. Algorithm to detect cycle in a linked list
In this program, we will use a user defined function "findloop" which takes a pointer to the head node of linked list as input from user and check whether linked list contains a cycle or not by implementing above algorithm. 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"); }C program to check cycle in linked list#includeInserted Element : 8 Inserted Element : 3 Inserted Element : 2 Inserted Element : 7 Inserted Element : 9 Linked List contains a loop Method 2 : Using a Hash Table. Algorithm to detect cycle in a linked list
|