Search code examples
loopsgolinked-listsingly-linked-list

Is it possible to create new linked list nodes inside a loop in goLang?


I need to create a nodes for a linked list and return the head inside a Function.

Definition for each node:

type ListNode struct {
    Val  int
    Next *ListNode
}

This is the function:


func addTwoNumbers(l1 *ListNode, l2 *ListNode) []string {

    calculateValue := func(l *ListNode) int {
        var sumsum int
        element := l
        weight := 1
        for element != nil {
            sumsum = sumsum + element.Val*weight
            weight = weight * 10
            element = element.Next
        }
        return sumsum
    }

    numstr := strconv.Itoa(calculateValue(l1) + calculateValue(l2))

    listsum := strings.Split(numstr, "")

    return listsum

}

Right now the function returns a list of strings, each string should be assigned to Val in each node.(Val is an integer and right now the list is of string I can handle that later).

So the idea would be to iterate through a list with a for loop and create the nodes and link them together inside a for. It would look something like this (inside addTwoNumbers before the return):

    for _, element := range listsum{
        

    }

Is there a way this can be done?


Solution

  • Solution mentioned in comment

    // create head with the value from first element
    head := &ListNode{ Val: listSum[0] }
    
    tail := head
    // range remaining values
    for _, sum := range listSum[1:] {
        node := &ListNode{ Val: sum }
        tail.Next = node // append node to list
        tail = node // change tail pointer to currently added node
    }