I'm new to Golang and am a bit confused as to how pointers work here and I'm using a reverse linked list question as an example.
func reverseList(head *ListNode) *ListNode {
var prev *ListNode = nil
for {
if head == nil {
break
}
temp := head
head = head.Next
temp.Next = prev
prev = temp
}
return prev
}
In this case, temp and head is pointing to the same memory location. But if I were to put the line temp.Next = prev before head = head.Next, the head.Next will point to nil.
What is happening under the hood when we say temp.Next = prev. Are we saying that the structure temp is pointing at is now changed and thus if I were to put that line above head = head.Next then head is now pointing to this changed structure as well?
I thought in order to change the actual value of head.Next, we would have to dereference it?
I'm a little bit confused as to why this wouldn't work instead
func reverseList(head *ListNode) *ListNode {
var prev *ListNode = nil
for {
if head == nil {
break
}
temp := head
temp.Next = prev
prev = temp
head = head.Next <--- CHANGED ORDERING HERE
}
return prev
}
p.Nextifpis a pointer or ifpis a struct variable.