Skip to content

Commit 507ed2e

Browse files
author
DuLi
committed
add linked list sum
1 parent 6bf644f commit 507ed2e

File tree

1 file changed

+37
-0
lines changed
  • Leetcode/Linked List/#2-Add Two Numbers

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*/
8+
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
9+
dummy := &ListNode{}
10+
head := dummy
11+
count := 0
12+
for l1 != nil || l2 != nil {
13+
base := 0
14+
if l1 != nil {
15+
base += l1.Val
16+
l1 = l1.Next
17+
}
18+
if l2 != nil {
19+
base += l2.Val
20+
l2 = l2.Next
21+
}
22+
base += count
23+
if base > 9 {
24+
dummy.Next = &ListNode{Val: base - 10}
25+
count = 1
26+
} else {
27+
dummy.Next = &ListNode{Val: base}
28+
count = 0
29+
}
30+
dummy = dummy.Next
31+
}
32+
33+
if count == 1 {
34+
dummy.Next = &ListNode{Val: 1}
35+
}
36+
return head.Next
37+
}

0 commit comments

Comments
 (0)