-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular linked list.py
53 lines (44 loc) · 1.21 KB
/
circular linked list.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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
if self.head is None:
self.head = Node(data)
self.head.next = self.head
else:
new_node = Node(data)
temp = self.head
while temp.next != self.head:
temp = temp.next
temp.next = new_node
new_node.next = self.head
def prepend(self, data):
new_node = Node(data)
temp = self.head
new_node.next = self.head
if not self.head:
new_node.next = new_node
else:
while temp.next != self.head:
temp = temp.next
temp.next = new_node
self.head = new_node
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
if temp == self.head:
break
if __name__ == '__main__':
clist = CircularLinkedList()
clist.append("C")
clist.append("D")
clist.prepend("B")
clist.prepend("A")
clist.append("E")
clist.printList()