leetcode(2)两数相加

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp = 0;
        int jinwei = 0;
        ListNode head = new ListNode(0);
        ListNode node = head;
        ListNode lastNode = null;
        while(l1!=null&&l2!=null){
            temp = l1.val + l2.val + jinwei;
            lastNode = node;
            node =  new ListNode(temp%10);
            jinwei = temp/10;
            lastNode.next = node;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1!=null){
           temp = l1.val + jinwei;
           lastNode = node;
           node =  new ListNode(temp%10);
           jinwei = temp/10;
           lastNode.next = node;
           l1 = l1.next;
        }
        while(l2!=null){
           temp = l2.val + jinwei;
           lastNode = node;
           node =  new ListNode(temp%10);
           jinwei = temp/10;
           lastNode.next = node;
           l2 = l2.next;
        }
        if(jinwei != 0){
           lastNode = node;
           node =  new ListNode(jinwei);
           lastNode.next = node;
        }
        return head.next;
    } 
}
原文地址:https://www.cnblogs.com/erdanyang/p/11064259.html