The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet87/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   83   84   85   86   87   88   89   90   ...   147
Bog'liq
books-library.net-11301817Az7X6

a
b
c
a
c
Figure 10.8: To remove a node, change the previous 
node’s pointer.


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



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   83   84   85   86   87   88   89   90   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling