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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1==null) {
            return l2;
        }
        if (l2==null) {
            return l1;
        }
        ListNode tail=null,p1=l1,p2=l2;
        //进位的数字
        int add = 0;
        ListNode head = null;
        while (p1!=null && p2!=null) {
            int sum = p1.val+p2.val+add;
            add = (sum)/10;
            if (tail==null) {
                tail = new ListNode((sum)%10);
                head = tail;
            } else {
                tail.next = new ListNode((sum)%10);
                tail = tail.next;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        while (p1!=null) {
            int sum = p1.val+add;
            add = (sum)/10;
            tail.next = new ListNode((sum)%10);
            tail = tail.next;
            p1 = p1.next;
        }
        while (p2!=null) {
            int sum = p2.val+add;
            add = (sum)/10;
            tail.next = new ListNode((sum)%10);
            tail = tail.next;
            p2 = p2.next;
        }
        //最后一位 如果还有进位,需要加一位
        if (add!=0) {
            tail.next = new ListNode(add);
        }
        return head;
    }
}
原文地址:https://www.cnblogs.com/23lalala/p/3506902.html