Add two numbers

题目: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

没啥好说的,类似与merge list的过程。对余下的list的操作可以合并,使代码看起来简洁。就是那个意思,体会一下。。。

 1     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         ListNode A = l1;
 3         ListNode B = l2;
 4         int carry = 0;
 5         ListNode newHead = new ListNode(0);
 6         ListNode cur = newHead;
 7         while(A != null || B != null){
 8             if (A != null){
 9                 carry += A.val;
10                 A = A.next;
11             }
12             if (B != null){
13                 carry += B.val;
14                 B = B.next;
15             }
16             cur.next = new ListNode(carry % 10);
17             cur = cur.next;
18             carry /= 10;
19         }
20         if (carry == 1) {
21             cur.next = new ListNode(1);
22         }
23         return newHead.next;
24     }
原文地址:https://www.cnblogs.com/gonuts/p/4406564.html