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
Release: 2024-02-06 11:33:09
forward
549 people have browsed it

运行时错误:无效的内存地址或 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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template