Skip to content

Commit 5d03754

Browse files
committed
circular linked list
1 parent 0d9cd3c commit 5d03754

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

circular linked list.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
7+
class CircularLinkedList:
8+
def __init__(self):
9+
self.head = None
10+
11+
def append(self, data):
12+
if self.head is None:
13+
self.head = Node(data)
14+
self.head.next = self.head
15+
else:
16+
new_node = Node(data)
17+
temp = self.head
18+
while temp.next != self.head:
19+
temp = temp.next
20+
temp.next = new_node
21+
new_node.next = self.head
22+
23+
def prepend(self, data):
24+
new_node = Node(data)
25+
temp = self.head
26+
new_node.next = self.head
27+
if not self.head:
28+
new_node.next = new_node
29+
else:
30+
while temp.next != self.head:
31+
temp = temp.next
32+
temp.next = new_node
33+
self.head = new_node
34+
35+
def printList(self):
36+
temp = self.head
37+
while temp:
38+
print(temp.data)
39+
temp = temp.next
40+
if temp == self.head:
41+
break
42+
43+
44+
if __name__ == '__main__':
45+
46+
clist = CircularLinkedList()
47+
clist.append("C")
48+
clist.append("D")
49+
clist.prepend("B")
50+
clist.prepend("A")
51+
clist.append("E")
52+
clist.printList()
53+

0 commit comments

Comments
 (0)