Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add linked list detect cycle algorithm in Python #6821

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion code/data_structures/src/DoubleLinkedList/Doubly linked list.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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")