Converting an array into a linked list in Golang

Viewed 178

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]
2 Answers

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
}

Change convertToList:

func convertToList(arr []int) *ListNode {
    head := new(ListNode)
    if len(arr) == 0 {
        return head
    }
    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
}

See this like : linked list for more information

Related