@@ -4,11 +4,11 @@ class Node:
44 Stores a value and links to the people ahead and behind.
55 """
66 __slots__ = ['value' , 'next' , 'previous' ]
7-
7+
88 def __init__ (self , value ):
99 self .value = value
10- self .next = None # The person ahead
11- self .previous = None # The person behind
10+ self .next = None
11+ self .previous = None
1212
1313
1414class LinkedList :
@@ -23,61 +23,51 @@ def push_head(self, value):
2323 """Adds a new node to the front of the list."""
2424 new_node = Node (value )
2525
26- # Logic 2: If the list is empty
2726 if self .head is None :
2827 self .head = new_node
2928 self .tail = new_node
30- # Logic 3: If the list is not empty
29+
3130 else :
32- new_node .next = self .head # New person grabs old head's hand
33- self .head .previous = new_node # Old head reaches back to new person
34- self .head = new_node # New person is now the head
31+ new_node .next = self .head
32+ self .head .previous = new_node
33+ self .head = new_node
3534
36- # Logic 4: Return the node so we can reference it later
3735 return new_node
3836
3937 def pop_tail (self ):
4038 """Removes the last node and returns its value."""
41- # Safety check: if list is empty
39+
4240 if self .tail is None :
4341 return None
4442
45- # Logic 1: Store the value to return later
4643 value_to_return = self .tail .value
4744
48- # Logic 2: If there is only one person in line
4945 if self .head == self .tail :
5046 self .head = None
5147 self .tail = None
52- # Logic 3: If there are more people
48+
5349 else :
5450 self .tail = self .tail .previous # Move tail back one
5551 self .tail .next = None # New tail lets go of the old tail
5652
57- # Logic 4: Return the name/value
5853 return value_to_return
5954
6055 def remove (self , node ):
6156 """Removes a specific node from anywhere in the list."""
6257 if node is None :
6358 return
6459
65- # Logic 3: Update Head/Tail pointers if the node is at the ends
6660 if node == self .head :
6761 self .head = node .next
6862
6963 if node == self .tail :
7064 self .tail = node .previous
7165
72- # Logic 1 & 2: Re-link the neighbors
73- # If there's someone behind, they skip over 'node' to grab 'node.next'
7466 if node .previous is not None :
7567 node .previous .next = node .next
7668
77- # If there's someone ahead, they reach back to grab 'node.previous'
7869 if node .next is not None :
7970 node .next .previous = node .previous
8071
81- # Optional: Clean up the removed node's own pointers
8272 node .next = None
8373 node .previous = None
0 commit comments