From c7e6a95556463c600315bd3d5d485ce5f94ba145 Mon Sep 17 00:00:00 2001 From: jdjones429 <155858126+jdjones429@users.noreply.github.com> Date: Wed, 6 Nov 2024 15:11:25 -0500 Subject: [PATCH] Update Doubly linked list.py Added linked list detect cycle algorithm, and also updated the program instructions and options to include this new option. --- .../src/DoubleLinkedList/Doubly linked list.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/code/data_structures/src/DoubleLinkedList/Doubly linked list.py b/code/data_structures/src/DoubleLinkedList/Doubly linked list.py index 4bece7f9a5..52062b733e 100644 --- a/code/data_structures/src/DoubleLinkedList/Doubly linked list.py +++ b/code/data_structures/src/DoubleLinkedList/Doubly linked list.py @@ -57,9 +57,18 @@ def Delete(self, data): current.prev = prev.next def Empty(self): return self.ptr == None + def HasCycle(self): + slow = self.ptr + fast = self.ptr + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + return False dll = DLL() while True: - choice = int(input("\n1.Insert\n2.Delete\n3.Check Empty\n4.Exit\nEnter Choice : ")) + choice = int(input("\n1.Insert\n2.Delete\n3.Check Empty\n4.Detect Cycle\n5.Exit\nEnter Choice : ")) if choice == 1: value = int(input("Enter element to Insert : ")) dll.Insert(value) @@ -71,5 +80,10 @@ def Empty(self): elif choice == 3: print(dll.Empty()) elif choice == 4: + if dll.HasCycle(): + print("Cycle detected in the linked list") + else: + print("No cycle detected in the linked list") + elif choice == 5: break print("Program End")