-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTORTOISE & HARE
40 lines (40 loc) · 1.1 KB
/
TORTOISE & HARE
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
class Node: #node creation
def __init__(self,data):
self.data=data
self.next=None
class Llist: #main logic for list
def __init__(self):
self.head=None
def build(self,data):
new_node=Node(data) #calling Node class for creation of new_node
if self.head is None:
self.head=new_node
else:
temp=self.head
while temp.next is not None:
temp=temp.next
temp.next=new_node
#TORTOISE & HARE APPROACH
def find_middle(self):
slow=self.head
fast=self.head
#Traverse the list with two pointers
while fast is not None and fast.next is not None:
slow=slow.next
fast=fast.next
return slow
def display(self):
temp=self.head
while temp is not None:
print(temp.data,end="->")
temp=temp.next
print("None")
l1=Llist()
l1.build(1)
l1.build(2)
l1.build(4)
l1.build(5)
print("List 1:")
l1.display()
middle_node=l1.find_middle()
print("Middle Node:",middle_node.data if middle_node else "List is empty")