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.
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!