My question is that when I made the head point to head.next
the input.Val still remains 1 instead of 2(which is the next value).
type ListNode struct {
Val int
Next *ListNode
}
func test(head *ListNode) *ListNode {
head = head.Next
return head
}
func main() {
var input, input2 ListNode
input = ListNode{Val: 1, Next: &input2}}
input2 = ListNode{Val: 2}
test(&input)
fmt.Println(input.Val)
}
Here it is fixed:
https://play.golang.org/p/VUeqh71nEaN
package main
import (
"fmt"
)
type ListNode struct {
Val int
Next *ListNode
}
func test(head *ListNode) *ListNode {
head = head.Next
return head
}
func main() {
var input1, input2 ListNode
input1 = ListNode{Val: 1, Next: &input2}
input2 = ListNode{Val: 2, Next: &input1}
input := test(&input1)
fmt.Println(input.Val)
}
Outputs
2
The problems were that you don't use the return value of your test
function, and you passed a node that doesn't have a Next
value.