-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircularSingleLinkedList.py
138 lines (126 loc) · 3.58 KB
/
CircularSingleLinkedList.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class Node:
def __init__(self, data):
self.data = data
self.ref = None
class CircularLinkedList:
def __init__(self):
self.head = None
def printCLL(self):
if self.head is None:
print("List is empty")
else:
n = self.head
while True:
print(n.data, "-->", end=" ")
n = n.ref
if n == self.head:
break
print()
def add_begin(self, item):
new_node = Node(item)
if self.head is None:
self.head = new_node
new_node.ref = self.head
else:
n = self.head
while n.ref != self.head:
n = n.ref
new_node.ref = self.head
n.ref = new_node
self.head = new_node
def add_end(self, item):
new_node = Node(item)
if self.head is None:
self.head = new_node
new_node.ref = self.head
else:
n = self.head
while n.ref != self.head:
n = n.ref
n.ref = new_node
new_node.ref = self.head
def add_before(self, item, x):
if self.head is None:
print("List is empty")
return
if self.head.data == x:
self.add_begin(item)
return
n = self.head
while n.ref != self.head:
if n.ref.data == x:
break
n = n.ref
if n.ref == self.head:
print("Node not found")
else:
new_node = Node(item)
new_node.ref = n.ref
n.ref = new_node
def add_after(self, item, x):
if self.head is None:
print("List is empty")
return
n = self.head
while True:
if n.data == x:
break
n = n.ref
if n == self.head:
print("Node not found")
return
new_node = Node(item)
new_node.ref = n.ref
n.ref = new_node
def delete_begin(self):
if self.head is None:
print("List is empty")
else:
if self.head.ref == self.head:
self.head = None
else:
n = self.head
while n.ref != self.head:
n = n.ref
n.ref = self.head.ref
self.head = self.head.ref
def delete_end(self):
if self.head is None:
print("List is empty")
else:
if self.head.ref == self.head:
self.head = None
else:
n = self.head
while n.ref.ref != self.head:
n = n.ref
n.ref = self.head
def delete_value(self, x):
if self.head is None:
print("List is empty")
elif self.head.data == x:
self.delete_begin()
else:
n = self.head
while n.ref != self.head:
if n.ref.data == x:
break
n = n.ref
if n.ref == self.head:
print("Node not found")
else:
n.ref = n.ref.ref
CLL = CircularLinkedList()
CLL.add_begin(10)
CLL.add_begin(20)
CLL.add_end(30)
CLL.add_end(40)
CLL.add_before(25, 30)
CLL.add_after(35, 30)
CLL.printCLL()
CLL.delete_begin()
CLL.printCLL()
CLL.delete_end()
CLL.printCLL()
CLL.delete_value(25)
CLL.printCLL()