Skip to content

Commit 51d82bf

Browse files
Adding some files
1 parent 79a931c commit 51d82bf

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
from unittest import TestCase
2+
3+
"""
4+
Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the
5+
beginning of the loop.
6+
DEFINITION
7+
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list.
8+
EXAMPLE
9+
Input: A -> B -> C -> D -> E -> C [thesameCasearlier]
10+
Output: C
11+
Hints: #50, #69, #83, #90
12+
"""
13+
14+
class Node:
15+
#Singly link list
16+
def __init__(self,data = None):
17+
self.data = data
18+
self.next = None
19+
20+
class linklist:
21+
#linkList class
22+
def __init__(self):
23+
self.head = None
24+
self.size = 0
25+
26+
def getSize(self):
27+
return self.size
28+
29+
def push(self,data):
30+
node = Node(data)# create a new node
31+
32+
if self.head == None: #check to see if the head node is empty
33+
self.head = node # If its empty add it to the new node
34+
self.size = 1
35+
return
36+
#if the head of the linklist is filled
37+
38+
current = self.head
39+
while current.next is not None:#Check the current postion is empty
40+
#Move to the next line if nothing is there
41+
current = current.next
42+
43+
44+
current.next = node #point self.head to a new node
45+
self.size+=1
46+
47+
def lenght(self):
48+
#note the count doesn't start at zero
49+
cur = self.head
50+
counter = 0
51+
while cur is not None:
52+
counter+=1
53+
cur = cur.next
54+
print('Linklist len: '+str(counter))
55+
return counter
56+
57+
def printList(self):
58+
curr = self.head
59+
elem = []
60+
61+
while(curr != None):
62+
elem.append(curr.data)
63+
curr = curr.next
64+
print(elem)
65+
#1->2->3
66+
def remove_node(self,data):
67+
#1->2->3
68+
curr = self.head
69+
if curr is not None and curr.data == data:
70+
self.head = curr.next
71+
curr = None
72+
#look for the node that has the data we are looking for
73+
while curr is not None:
74+
if curr.data == data:
75+
break
76+
prev = curr
77+
curr = curr.next
78+
79+
#if data isn't found just reutrn
80+
if(curr == None):
81+
return
82+
83+
#allow us to unlink the nodes
84+
prev.next = curr.next
85+
curr = None
86+
def loopDetection(self):
87+
p1 = p2 = self.head
88+
89+
while p1 and p2:
90+
#runner
91+
p1 = p1.next
92+
p2 = p2.next.next
93+
if p1 == p2:
94+
return True
95+
else:
96+
return False
97+
98+
99+
100+
101+
102+
103+
llist = linklist()
104+
llist.push(1)
105+
llist.push(2)
106+
llist.push(3)
107+
llist.head.next.next = llist.head.next # make my loop
108+
print(llist.loopDetection())

0 commit comments

Comments
 (0)