@@ -86,8 +86,49 @@ def shift(self):
86
86
def pop (self ) -> Optional [Node ]:
87
87
pass
88
88
89
- def delete_node (self , n : Node ):
90
- pass
89
+ def delete_node (self , node_ : CircularNode ):
90
+ if self .head :
91
+ # if the head node matches the node we are looking for
92
+ if self .head == node_ :
93
+ # set the current pointer to the head node. This will be used to track the last node as the pointer
94
+ # moves through the list
95
+ current = self .head
96
+ # move through the list until we reach the pointer that points batck to the head node.
97
+ while current .next != self .head :
98
+ current = current .next
99
+
100
+ # if the head node equals the next node, that means that this linked list has a length of 1, i.e. just 1
101
+ # node. The head node can be set to None
102
+ if self .head == self .head .next :
103
+ self .head = None
104
+ else :
105
+ # set the current pointer to point to the current head's next
106
+ current .next = self .head .next
107
+ # set the head to now become the next node
108
+ self .head = self .head .next
109
+ else :
110
+ # we have a situation where the head node's key is not equal to the head node, therefore, we need to
111
+ # traverse the list to find the first node whose key matches the given key. Setting current to the head
112
+ # node acts as the pointer that we keep track of
113
+ current = self .head
114
+ # previous pointer helps to keep track of the previous node as we traverse, it is initially set to None
115
+ previous : Optional [CircularNode ] = None
116
+
117
+ # we iterate through the linked list as long as the next pointer of the current head is not equal to
118
+ # the head node. This is to avoid an infinite loop as this is a circular linked list.
119
+ while current .next != self .head :
120
+ # we set the previous pointer to the current node to keep track of the node before we reset the
121
+ # current pointer to the next node
122
+ previous = current
123
+ # move the current pointer to the next node
124
+ current = current .next
125
+ # if the current node's key is equal to the key we are searching for
126
+ if current == node_ :
127
+ # we set the previous node's next pointer to point to the current node's next pointer.
128
+ # Essentially removing the current node from the list
129
+ previous .next = current .next
130
+ # set the current node to the current's next node
131
+ current = current .next
91
132
92
133
def delete_node_at_position (self , position : int ):
93
134
pass
0 commit comments