add-two-numbers

add-two-numbers

give you two linked list that non-empty and the digits is reversed store by them. you need to add every node of them and returen the sum as a linked list

  • key info
    • linkedList
    • go
    • simulation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
headNode := &ListNode{}
curNode := headNode

cur_flag := 0

for l1!=nil || l2!=nil {
l1Val := 0
l2Val := 0
if l1!=nil {
l1Val = l1.Val
l1 = l1.Next
}
if l2!=nil {
l2Val = l2.Val
l2 = l2.Next
}
tempRes := l1Val + cur_flag + l2Val
if tempRes >=10 {
tempRes -=10
cur_flag = 1
}else {
cur_flag = 0
}
temNode := &ListNode{}
temNode.Val = tempRes
curNode.Next = temNode
curNode = curNode.Next
}
if cur_flag==1 {
tempNode := &ListNode{}
tempNode.Val = 1
curNode.Next = tempNode
}
return headNode.Next
}

add-two-numbers
http://orikey0.github.io/2024/02/09/add-two-numbers/
作者
Howard Lee
发布于
2024年2月9日
许可协议