Chapter 10 Linked Lists
109
If it is, you set
self.head
to the next node in your list and return.
Otherwise, you iterate
through your linked list, keeping track of both the current node and the
previous
node in the variables
current
and
previous
:
current = self.head
previous = None
Next, you use a
while
loop to iterate through your linked list. If you find
the data you are looking
for, you set
previous.next
to
current.next
, which removes the node from your list:
while current:
if current.data == target:
previous.next = current.next
previous = current
current = current.next
Reverse a Linked List
You should also know how to reverse a linked list.
To reverse a linked list, you iterate through the
list, keeping track of both the current node and the previous node. Then,
you make the current node
point to the previous node. Once you’ve changed all the pointers in your linked list, you’ve reversed
it (Figure 10.9).
Let’s take a look at the code to reverse a linked list:
def reverse_list(self):
current = self.head
previous = None
while current:
next = current.next
current.next = previous
previous = current
current = next
self.head = previous
a
a
b
Points
to Next
Points to
Previous
current
b
current
Figure 10.9: Reversing a linked list