skip to Main Content

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


  1. Let’s say you have a linked list with two nodes: [1]-[2]

    initial:
    fast = [1]
    slow = [1]
    
    first iteration (fast.next = [2] != null)
    fast = fast.next.next = null
    slow = slow.next = [2]
    
    second iteration (attempts to check fast.next = (null.next) => raises TypeError)
    

    The fix is to change your condition to check both fast && fast.next. You can then remove the if check as well.

    const middleNode = (head) => {
        let fast = head;
        let slow = head;
    
        while (fast && fast.next) { // fast != null && fast.next != null
            fast = fast.next.next;
            slow = slow.next;
            
        }
        return slow;
    }
    
    Login or Signup to reply.
  2. If fast.next doesn’t have a next node fast.next.next will be null therefore on the next iteration when you check

    fast.next !== null
    

    You are trying to access the next propriety on a null object. You could check if fast exist first like this :

    while (fast!=null && fast.next !== null) {
                fast = fast.next.next
                slow = slow.next
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search