2. Add Two Numbers[Medium]链表

2. Add Two Numbers
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        p = dummy = ListNode(-1)
        num = carry = 0
        while l1 or l2 or carry:
            num1 = l1.val if l1 else 0
            num2 = l2.val if l2 else 0
            num = num1 + num2 + carry
            node = ListNode(num % 10)
            carry = num // 10
            p.next = node
            p = node
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return dummy.next
/**
 * 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) {
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        ListNode l3 = new ListNode(-1);
        ListNode p = l3;
        int carry = 0;
        while(l1!=null || l2!=null){
            int sum = 0;
            if(l1 != null){
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                sum += l2.val;
                l2 = l2.next;
            }
            sum += carry;
            ListNode temp = new ListNode(sum%10);
            p.next = temp;
            carry = sum / 10;
            p = p.next;
        }
        if(carry==1){
            ListNode temp = new ListNode(carry);
            p.next = temp;
        }
        return l3.next;
    }
}

你可能感兴趣的:(2. Add Two Numbers[Medium]链表)