【LeetCode】2. 两数相加(gloang)

package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func main() {
	aList1 := &ListNode{Val: 1}
	bList1 := &ListNode{Val: 9}
	bList1.Next = &ListNode{Val: 9}
	cList := addTwoNumbers(aList1, bList1)
	fmt.Println(cList)
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	cList := &ListNode{}
	curr := cList
	first := l1
	second := l2
	//进位
	carry := 0
	for first != nil || second != nil {
		val1 := 0
		val2 := 0
		if first != nil {
			val1 = first.Val
		}
		if second != nil {
			val2 = second.Val
		}
		sum := carry + val1 + val2
		carry = sum / 10
		curr.Val = sum % 10
		if first != nil {
			first = first.Next
		}
		if second != nil {
			second = second.Next
		}
		if first != nil || second != nil {
			curr.Next = &ListNode{}
			curr = curr.Next
		}
	}
	if carry != 0 {
		curr.Next = &ListNode{Val: carry}
	}
	return cList
}

你可能感兴趣的:(leetcode,golang,两数相加)