forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove_loop.py
73 lines (61 loc) · 1.85 KB
/
remove_loop.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class LinkedList:
head = None
# head of list
# Linked list Node
class Node:
data = 0
next = None
def __init__(self, d):
self.data = d
self.next = None
# Inserts a new Node at front of the list.
@staticmethod
def push(new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = LinkedList.Node(new_data)
# 3. Make next of new Node as head
new_node.next = LinkedList.head
# 4. Move the head to point to new Node
LinkedList.head = new_node
# Function to print the linked list
def printList(self, node):
while node != None:
print(node.data)
node = node.next
# Returns true if the loop is removed from the linked
# list else returns false.
@staticmethod
def removeLoop(h):
s = set()
prev = None
while h != None:
# If we have already has this node
# in hashmap it means their is a cycle and we
# need to remove this cycle so set the next of
# the previous pointer with null.
if h in s:
prev.next = None
return True
else:
s.add(h)
prev = h
h = h.next
return False
# Driver program to test above function
@staticmethod
def main(args):
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)
# Create loop for testing
llist.head.next.next.next.next = llist.head
if LinkedList.removeLoop(LinkedList.head):
print("Linked List after removing loop")
llist.printList(LinkedList.head)
else:
print("No Loop found")
if __name__ == "__main__":
LinkedList.main([])