find the sum of all nodes in a linked list in go

To find the sum of all nodes in a linked list, we can traverse the list and add up the values of each node. We can do this with a recursive or iterative approach.

Here's an iterative approach:

main.go
func sumLinkedList(head *ListNode) int {
    sum := 0
    current := head
    for current != nil {
        sum += current.Val
        current = current.Next
    }
    return sum
}
180 chars
10 lines

And here's a recursive approach:

main.go
func sumLinkedList(head *ListNode) int {
    if head == nil {
        return 0
    }
    return head.Val + sumLinkedList(head.Next)
}
134 chars
7 lines

In the recursive approach, we check if the list is empty (i.e. head is nil) and if so, return 0. Otherwise, we add the value of the current node to the sum of the rest of the list, which we compute recursively using sumLinkedList(head.Next).

gistlibby LogSnag