-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_cyclic.py
More file actions
57 lines (46 loc) · 1.34 KB
/
is_cyclic.py
File metadata and controls
57 lines (46 loc) · 1.34 KB
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
class Node:
def __init__(self):
self.data = None
self.next = None
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setNext(self, next):
self.next = next
class SinglyLinkedList:
# constructor
def __init__(self):
self.head = None
# method for setting the head of the Linked List
def setHead(self, head):
self.head = head
def insert(self, node):
if self.head is None:
self.setHead(node)
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = node
def create(self, data):
for item in data:
new_node = Node()
new_node.setData(item)
self.insert(new_node)
def is_cyclic(self):
if self.head is None:
return False
else:
fast = self.head.next
slow = self.head
while fast is not None and fast.data != slow.data:
slow = slow.next
fast = fast.next
if fast is not None and fast.data != slow.data:
fast = fast.next
return fast is not None
test = SinglyLinkedList()
test.create([1, 2, 3, 4])
test.head.next.next.next.next = test.head
print(test.is_cyclic())