'Converting an array into a linked list in Golang

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]


Solution 1:[1]

You have to change your convertToList and insert functions as:

func insert(root *ListNode, elem int) *ListNode {
    temp := ListNode{Val: elem, Next: nil}
    if root == nil {
        root = &temp
        return root
    }
    curr := root
    for curr.Next != nil {
        curr = curr.Next
    }
    curr.Next = &temp
    return root
}

and convertToList:

func convertToList(arr []int) *ListNode {
    var head *ListNode
    for _, val := range arr {
        head = insert(head, val)
    }
    return head
}

Solution 2:[2]

Change convertToList:

func convertToList(arr []int) *ListNode {
    head := new(ListNode)
    head.Val = arr[0]
    head.Next = nil

    last := head
    for i := 1; i < len(arr); i++ {
        last = insert(last, arr[i])
    }
    return head
}

And insert:

func insert(last *ListNode, val int) *ListNode {
    temp := new(ListNode)
    temp.Val = val
    temp.Next = nil
    last.Next = temp
    return last.Next
}

Note : you can't normally shown linked list. If you print list, understood.

// for show linked list:
func Print(head *ListNode) {
    fmt.Print("[ ")
    for temp := head; temp != nil; temp = temp.Next {
        fmt.Print(temp.Val, " ")
    }
    fmt.Print("]\n")
}
func main() {
    arr := []int{1, 2, 3, 4, 5}
    listNode := convertToList(arr) 
    // You can see different:
    fmt.Println("List:", listNode) // List: &{1 0xc00009a080}
    Print(listNode)               // [ 1 2 3 4 5 ]
}

See this like : linked list for more information

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sarkan
Solution 2