题目:两个链表存储数字,然后求和,和值存储在一个链表中。
代码:
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
2 ListNode head = new ListNode(0);
3 ListNode result = head;
4
5 int carry = 0 , tempSum = 0;
6 while(l1 != null || l2 != null){
7 int v1 , v2;
8 v1 = (l1 != null) ? l1.val : 0;
9 v2 = (l2 != null) ? l2.val : 0;
10 tempSum = v1 + v2 + carry;
11 carry = tempSum / 10;
12 tempSum = tempSum % 10;
13 head.next = new ListNode(tempSum);
14 head = head.next;
15
16 l1 = (l1 != null) ? l1.next : null;
17 l2 = (l2 != null) ? l2.next : null;
18 }
19
20 if(carry > 0) head.next = new ListNode(carry);
21
22 return result.next;
23 }
[leetcode]_Add Two Numbers,布布扣,bubuko.com
时间: 2024-08-21 13:09:43