definition of linked list:
type ListNode struct {
Val int
Next *ListNode
}
insert helper that does the pointer manipulation: I am aware that root.Val == 0 is does not solve problems where the input array contains 0 elements, so please suggest a more general approach to solve this.
func insert(root *ListNode, elem int) *ListNode {
temp := ListNode{Val: elem, Next: nil}
if root.Val == 0 {
root = &temp
} else {
curr := root
for curr.Next != nil {
curr = curr.Next
}
curr = &temp
}
return root
}
The main functionality:
func convertToList(arr []int) *ListNode {
var head ListNode
for _, val := range arr {
head = *insert(&head, val)
}
return &head
}
A string function implementation to test the function:
func (l *ListNode) String() string {
x := make([]int, 0)
curr := l
for curr != nil {
x = append(x, curr.Val)
curr = curr.Next
}
return fmt.Sprint(x)
}
My main function to replicate output:
func main() {
arr := []int{1, 2, 3, 4, 5}
listNode := convertToList(arr)
fmt.Println(listNode.String())
}
Output:
[1]
Expected Output:
[1 2 3 4 5]