i got panic: runtime error: invalid memory address or nil pointer deference
on for-loop condition fast!=nil && fast.Next!=nil when test with head=nil.
but it goes well if call middleNode from main or place this condition in if-else.
type Node struct{
Value int
Next *Node
}
func middleNode(head *Node) *Node {
sentinel := &Node{Next:head}
slow, fast := sentinel, sentinel
for fast!=nil && fast.Next!=nil {
slow = slow.Next
fast = fast.Next
if fast == nil{
return slow
}
fast = fast.Next
if fast == nil{
return slow
}
}
return slow
}
this’s my code
New contributor
user25733111 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.