I'm confused about how the while loop condition works in a linked list when checking for the middle node of a linked list
This is the correct code that I have for finding the middle node of a linked list
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class linkedList(object):
def __init__(self):
self.head = None
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
def middle(self):
first = self.head
second = self.head
while second and second.next:
second = second.next.next
first = first.next
print(first.data)
If I change the while loop to
while second:
or
while second.next:
I receive an error that says
AttributeError: 'NoneType' object has no attribute 'next' on line 24
I'm just wondering why it's important to have both second
and second.next
The solution works by using two pointers. First one takes 1 step at a time and second 2 steps at a time. However, in taking 2 steps there are two things to verify:
If you skip one check it will enter the loop but at the boundary condition it not find the next. To illustrate: If there are 4 nodes and you only check for second.next
at the 3nd node you'll have second.next
as valid and you'll enter the while
loop but inside that you are directly accessing second.next.next
F,S | 1 --> 2 --> 3 --> 4 --> None
For starters, your append method doesn't work, and gets stuck in an infinite while loop, since you don't exit out of append on adding the first element. The correct version is
def append(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
As to your other question, we want to find the middle of the loop for both even and odd lists, the second.next
covers the odd list case, and the second
covers the even list case, since either the 2nd pointer will point to null, or it will be null itself, and if you use only one of them, you will get the error you described it, hence you need to have both conditions in the while loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.