|
29 | 29 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
30 | 30 |
|
31 | 31 | ```python
|
32 |
| - |
| 32 | +# Definition for singly-linked list. |
| 33 | +# class ListNode: |
| 34 | +# def __init__(self, val=0, next=None): |
| 35 | +# self.val = val |
| 36 | +# self.next = next |
| 37 | +class Solution: |
| 38 | + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: |
| 39 | + carry = 0 |
| 40 | + dummy = ListNode(-1) |
| 41 | + cur = dummy |
| 42 | + while l1 or l2 or carry: |
| 43 | + t = (0 if not l1 else l1.val) + (0 if not l2 else l2.val) + carry |
| 44 | + carry = t // 10 |
| 45 | + cur.next = ListNode(t % 10) |
| 46 | + cur = cur.next |
| 47 | + l1 = None if not l1 else l1.next |
| 48 | + l2 = None if not l2 else l2.next |
| 49 | + return dummy.next |
33 | 50 | ```
|
34 | 51 |
|
35 | 52 | ### **Java**
|
36 | 53 |
|
37 | 54 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
38 | 55 |
|
39 | 56 | ```java
|
| 57 | +/** |
| 58 | + * Definition for singly-linked list. |
| 59 | + * public class ListNode { |
| 60 | + * int val; |
| 61 | + * ListNode next; |
| 62 | + * ListNode() {} |
| 63 | + * ListNode(int val) { this.val = val; } |
| 64 | + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 65 | + * } |
| 66 | + */ |
| 67 | +class Solution { |
| 68 | + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
| 69 | + int carry = 0; |
| 70 | + ListNode dummy = new ListNode(-1); |
| 71 | + ListNode cur = dummy; |
| 72 | + while (l1 != null || l2 != null || carry != 0) { |
| 73 | + int t = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; |
| 74 | + carry = t / 10; |
| 75 | + cur.next = new ListNode(t % 10); |
| 76 | + cur = cur.next; |
| 77 | + l1 = l1 == null ? null : l1.next; |
| 78 | + l2 = l2 == null ? null : l2.next; |
| 79 | + } |
| 80 | + return dummy.next; |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
40 | 84 |
|
| 85 | +### **C#** |
| 86 | + |
| 87 | +```cs |
| 88 | +/** |
| 89 | + * Definition for singly-linked list. |
| 90 | + * public class ListNode { |
| 91 | + * public int val; |
| 92 | + * public ListNode next; |
| 93 | + * public ListNode(int val=0, ListNode next=null) { |
| 94 | + * this.val = val; |
| 95 | + * this.next = next; |
| 96 | + * } |
| 97 | + * } |
| 98 | + */ |
| 99 | +public class Solution { |
| 100 | + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { |
| 101 | + ListNode dummy = new ListNode(-1); |
| 102 | + ListNode cur = dummy; |
| 103 | + var carry = 0; |
| 104 | + while (l1 != null || l2 != null || carry != 0) |
| 105 | + { |
| 106 | + int t = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; |
| 107 | + carry = t / 10; |
| 108 | + cur.next = new ListNode(t % 10); |
| 109 | + cur = cur.next; |
| 110 | + l1 = l1 == null ? null : l1.next; |
| 111 | + l2 = l2 == null ? null : l2.next; |
| 112 | + } |
| 113 | + return dummy.next; |
| 114 | + } |
| 115 | +} |
41 | 116 | ```
|
42 | 117 |
|
43 | 118 | ### **...**
|
|
0 commit comments