Skip to content

Commit ede19a9

Browse files
committed
Added implementation of Circularly Linked List
1 parent d4ae6bf commit ede19a9

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed

pygorithm/data_structures/linked_list.py

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def delete(self, data):
118118
# node not found
119119
if temp is None:
120120
return
121-
121+
122122
# TODO: local variable 'prev' might be referenced before assignment
123123
# TODO: Fix this
124124
prev.next = temp.next
@@ -214,3 +214,72 @@ def get_code():
214214
returns the code of the current class
215215
"""
216216
return inspect.getsource(DoublyLinkedList)
217+
218+
class CircularLinkedList(object):
219+
'''
220+
Class for circular linked list
221+
'''
222+
def __init__(self):
223+
self.head = None
224+
self.tail = None
225+
self.size = 0
226+
227+
def clear(self):
228+
''' clears the head and tails of the linked list '''
229+
self.tail = None
230+
self.head = None
231+
232+
def get_data(self):
233+
"""
234+
prints the elements in the linked list
235+
"""
236+
l_list = []
237+
current = self.tail
238+
while True:
239+
l_list.append(current.data)
240+
current = current.next
241+
if current == self.tail:
242+
break
243+
return l_list
244+
245+
def insert(self, data):
246+
''' inserts the data in to the linked list '''
247+
node = Node(data)
248+
if self.head:
249+
self.head.next = node
250+
self.head = node
251+
else:
252+
self.head = node
253+
self.tail = node
254+
self.head.next = self.tail
255+
self.size += 1
256+
257+
def delete(self, data):
258+
''' deletes the specified element from linked list '''
259+
current = self.tail
260+
prev = self.tail
261+
while prev == current or prev != self.head:
262+
if current.data == data:
263+
if current == self.tail:
264+
self.tail = current.next
265+
self.head.next = self.tail
266+
else:
267+
prev.next = current.next
268+
self.size -= 1
269+
return
270+
prev = current
271+
current = current.next
272+
273+
@staticmethod
274+
def get_code():
275+
"""
276+
returns the code of the current class
277+
"""
278+
return inspect.getsource(CircularLinkedList)
279+
280+
if __name__ == '__main__':
281+
cll = CircularLinkedList()
282+
cll.insert(1)
283+
cll.insert(2)
284+
cll.insert(3)
285+
print(cll.get_data())

0 commit comments

Comments
 (0)