Home >Backend Development >Golang >Runtime error: Invalid memory address or nil pointer dereferenced via cycle

Runtime error: Invalid memory address or nil pointer dereferenced via cycle

WBOY
WBOYforward
2024-02-06 11:33:09545browse

运行时错误:无效的内存地址或 nil 指针通过循环取消引用

Question content

I'm 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 reported an error: panic: Runtime error: Invalid memory address or nil pointer dereference. Please explain to me why this error occurs

Input: head = [1,2,3,4,5]. I want to loop 4 times until head.next == nil. But something unexpected happened.


Correct Answer


If head is nil -> head.next will give an error like the one you gave

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
}

More simply:

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
}

The above is the detailed content of Runtime error: Invalid memory address or nil pointer dereferenced via cycle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete