-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular_linked_list.py
147 lines (121 loc) · 3.63 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
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
139
140
141
142
143
144
145
146
class Node:
def __init__(self,item=None,next=None):
self.item=item
self.next=next
class Cll:
def __init__(self,last=None):
self.last=last
def is_empty(self):
return self.last==None
def insert_at_start(self,data):
n=Node(data)
if self.is_empty():
n.next=n
self.last=n
else:
n.next=self.last.next
self.last.next=n
def insert_at_last(self,data):
n=Node(data)
if self.is_empty():
n.next=n
self.last=n
else:
n.next=self.last.next
self.last.next=n
self.last=n
def search(self,data):
if self.is_empty():
return None
else:
temp=self.last.next
while temp!=self.last:
if temp.item==data:
return temp
else:
temp=temp.next
if temp.item==data:
return temp
return None
def insert_after(self,temp,data):
if temp is not None:
n=Node(data,temp.next)
temp.next=n
if self.last==temp:
self.last=n
def printlist(self):
if not self.is_empty():
temp=self.last.next
while temp!=self.last:
print(temp.item,end=' ')
temp=temp.next
print(temp.item)
def delete_first(self):
if not self.is_empty():
if self.last.next==self.last:
self.last=None
else:
self.last.next=self.last.next.next
def delete_last(self):
if not self.is_empty():
if self.last.next==self.last:
self.last=None
else:
temp=self.last.next
while temp.next!=self.last:
temp=temp.next
temp.next=self.last.next
self.last=temp
return "list is empty"
def delete_item(self,data):
if not self.is_empty():
if self.last.next==self.last:
if self.last.item==data:
self.last=None
else:
if self.last.next.item==data:
self.delete_first()
else:
temp=self.last.next
while temp!=self.last:
if temp.next==self.last:
if self.last.item==data:
self.delete_last()
break
if temp.next.item==data:
temp.next=temp.next.next
break
temp=temp.next
return "data not found"
def __iter__(self):
if self.last is None:
return CLLiterator(None)
else:
return CLLiterator(self.last.next)
class CLLiterator:
def __init__(self,start):
self.current=start
self.start=start
self.count=0
def __iter__(self):
return self
def __next__(self):
if self.current is None:
raise StopIteration
if self.current==self.start and self.count==1:
raise StopIteration
else:
self.count=1
data=self.current.item
self.current=self.current.next
return data
mylist=Cll()
mylist.insert_at_start(10)
mylist.insert_at_start(20)
mylist.insert_at_last(30)
mylist.insert_at_last(40)
mylist.insert_after(mylist.search(10),50)
mylist.printlist()
print()
for x in mylist:
print(x)