There is a task to find a middle of Linked List. Could you please explain why does fast.next
in while()
loop throw a "TypeError: Cannot read properties of null (reading ‘next’)"?
const middleNode = (head) => {
let fast = head
let slow = head
if (head !== null) {
while (fast.next !== null) {
fast = fast.next.next
slow = slow.next
}
}
return slow
}
2
Answers
Let’s say you have a linked list with two nodes:
[1]-[2]
The fix is to change your condition to check both
fast && fast.next
. You can then remove the if check as well.If fast.next doesn’t have a next node fast.next.next will be null therefore on the next iteration when you check
You are trying to access the next propriety on a null object. You could check if fast exist first like this :