GoLang with comments


  • 0
    A
    func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    	get := func(n *ListNode) ListNode { // get simplifies the code below, handling all nil pointers
    		if n != nil {
    			return *n
    		}
    		return ListNode{}
    	}
    
    	var resultRoot *ListNode // keeps track of the beginning of our result linked-list
    	r := &resultRoot         // pointer-to-pointer, so we can add to the tail of the result linked-list
    	carry := 0
    	for {
    		if l1 != nil || l2 != nil { // One or both of the lists have entries; if one is nil, it will feed zeros through get()
    			x := ListNode{Val: get(l1).Val + get(l2).Val + carry}
    			carry = x.Val / 10
    			x.Val %= 10
    			*r = &x     // Modify the pointer (e.g. resultRoot or tail.Next)
    			r = &x.Next // Update the pointer-to-pointer to point to tail.Next
    			l1, l2 = get(l1).Next, get(l2).Next
    			continue
    		}
    		if carry > 0 || r == &resultRoot { // If we have a final carry, or we never emitted any nodes, emit the carry (1 or 0)
    			x := ListNode{Val: carry}
    			*r = &x
    		}
    		break
    	}
    	return resultRoot
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.