Home > front end >  runtime error: invalid memory address or nil pointer dereference with loop
runtime error: invalid memory address or nil pointer dereference with loop

Time:01-06

I am trying to solve this problem: https://leetcode.com/problems/reverse-linked-list/description/?envType=study-plan&id=level-1

Input: head = [1,2,3,4,5]

This is my code:

func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    prev = nil
    for head.Next != nil {
        head, head.Next, prev = head.Next, prev, head
    }
    if head.Next == nil {
        head.Next = prev
    }
    return head
}

After running, the program gives an error: panic: runtime error: invalid memory address or nil pointer dereference. Please explain to me why this error occurs

With Input: head = [1,2,3,4,5]. I hope to do the loop 4 times until head.Next == nil. But something not as I expected happened.

CodePudding user response:

if head is nil -> head.Next will be error like you given

func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    prev = nil
    for head != nil && head.Next != nil {
        head, head.Next, prev = head.Next, prev, head
    }
    if  head != nil && head.Next == nil {
        head.Next = prev
    }
    return head
}

and more simple is :

func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    prev = nil
    for head != nil {
        head, head.Next, prev = head.Next, prev, head
    }
    if head == nil {
        head = prev
    }
    return head
}

CodePudding user response:

The error comes from for head.Next != nil, because if head is nil then you're dereferencing a nil pointer, which results in the panic.

To avoid this, you need to include a check that head is not nil.

You're code could look something like this:

func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    prev = nil
    if head != nil {
        for head.Next != nil {
            head, head.Next, prev = head.Next, prev, head
        }
        if head.Next == nil {
            head.Next = prev
        }
    }
    return head
}
  • Related