mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-04 16:12:47 +08:00
40 lines
701 B
Go
40 lines
701 B
Go
package leetcode
|
|
|
|
import (
|
|
"github.com/halfrost/LeetCode-Go/structures"
|
|
)
|
|
|
|
// ListNode define
|
|
type ListNode = structures.ListNode
|
|
|
|
/**
|
|
* Definition for singly-linked list.
|
|
* type ListNode struct {
|
|
* Val int
|
|
* Next *ListNode
|
|
* }
|
|
*/
|
|
|
|
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
|
|
head := &ListNode{Val: 0}
|
|
n1, n2, carry, current := 0, 0, 0, head
|
|
for l1 != nil || l2 != nil || carry != 0 {
|
|
if l1 == nil {
|
|
n1 = 0
|
|
} else {
|
|
n1 = l1.Val
|
|
l1 = l1.Next
|
|
}
|
|
if l2 == nil {
|
|
n2 = 0
|
|
} else {
|
|
n2 = l2.Val
|
|
l2 = l2.Next
|
|
}
|
|
current.Next = &ListNode{Val: (n1 + n2 + carry) % 10}
|
|
current = current.Next
|
|
carry = (n1 + n2 + carry) / 10
|
|
}
|
|
return head.Next
|
|
}
|