11"""
22https://en.wikipedia.org/wiki/Doubly_linked_list
33"""
4+ from __future__ import annotations
5+
6+ from typing import Any
47
58
69class Node :
7- def __init__ (self , data ):
10+ def __init__ (self , data : Any ):
811 self .data = data
9- self .previous = None
10- self .next = None
12+ self .previous : Node | None = None
13+ self .next : Node | None = None
1114
1215 def __str__ (self ):
1316 return f"{ self .data } "
1417
1518
1619class DoublyLinkedList :
1720 def __init__ (self ):
18- self .head = None
19- self .tail = None
21+ self .head : Node | None = None
22+ self .tail : Node | None = None
2023
2124 def __iter__ (self ):
2225 """
@@ -93,13 +96,18 @@ def insert_at_nth(self, index: int, data):
9396 new_node .next = self .head
9497 self .head = new_node
9598 elif index == length :
99+ assert self .tail is not None
96100 self .tail .next = new_node
101+ assert self .tail is not None
97102 new_node .previous = self .tail
98103 self .tail = new_node
99104 else :
100105 temp = self .head
106+ assert temp is not None
101107 for _ in range (index ):
102108 temp = temp .next
109+ assert temp is not None
110+ assert temp .previous is not None
103111 temp .previous .next = new_node
104112 new_node .previous = temp .previous
105113 new_node .next = temp
@@ -141,23 +149,32 @@ def delete_at_nth(self, index: int):
141149 if length == 1 :
142150 self .head = self .tail = None
143151 elif index == 0 :
152+ assert self .head is not None
144153 self .head = self .head .next
154+ assert self .head is not None
145155 self .head .previous = None
146156 elif index == length - 1 :
157+ assert self .tail is not None
147158 delete_node = self .tail
148159 self .tail = self .tail .previous
160+ assert self .tail is not None
149161 self .tail .next = None
150162 else :
151163 temp = self .head
164+ assert temp is not None
152165 for _ in range (index ):
153166 temp = temp .next
167+ assert temp is not None
154168 delete_node = temp
169+ assert temp .next is not None
170+ assert temp .previous is not None
155171 temp .next .previous = temp .previous
156172 temp .previous .next = temp .next
157173 return delete_node .data
158174
159175 def delete (self , data ) -> str :
160176 current = self .head
177+ assert current is not None
161178
162179 while current .data != data : # Find the position to delete
163180 if current .next :
@@ -172,6 +189,8 @@ def delete(self, data) -> str:
172189 self .delete_tail ()
173190
174191 else : # Before: 1 <--> 2(current) <--> 3
192+ assert current .previous is not None
193+ assert current .next is not None
175194 current .previous .next = current .next # 1 --> 3
176195 current .next .previous = current .previous # 1 <--> 3
177196 return data
0 commit comments