我正在尝试解决这个问题:https://leetcode.com/problems/reverse-linked-list/description/?envtype=study-plan&id=level-1
输入:head = [1,2,3,4,5]
这是我的代码:
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 }
运行后,程序报错:panic: 运行时错误: 无效的内存地址或 nil 指针取消引用。 请向我解释为什么会出现此错误
输入:head = [1,2,3,4,5]。我希望循环 4 次,直到 head.next == nil。但出乎我意料的事情发生了。
如果 head 是 nil -> head.next 将出现像您给出的错误
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 }
更简单的是:
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 }
以上是运行时错误:无效的内存地址或 nil 指针通过循环取消引用的详细内容。更多信息请关注PHP中文网其他相关文章!