002 Add Two Numbers 链表上的两数相加

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

详见:https://leetcode.com/problems/add-two-numbers/description/

Java实现:

/**
 * 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) {
        ListNode head=null;
        ListNode pre=null;
        int carry=0;
        while(l1!=null||l2!=null){
            int val1=l1!=null?l1.val:0;
            int val2=l2!=null?l2.val:0;
            int val=val1+val2+carry;
            carry=val/10;
            val%=10;
            ListNode cur=new ListNode(val);
            if(head==null){
                head=cur;
            }
            if(pre!=null){
                pre.next=cur;
            }
            pre=cur;
            l1=l1!=null?l1.next:null;
            l2=l2!=null?l2.next:null;
        }
        if(carry!=0){
            ListNode l=new ListNode(carry);
            pre.next=l;
        }
        return head;
    }
}

python:

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

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        head,pre,carry=None,None,0
        while l1 or l2:
            val1,val2=0,0
            if l1:
                val1=l1.val
                l1=l1.next
            if l2:
                val2=l2.val
                l2=l2.next
            val=val1+val2+carry
            carry=val//10
            val%=10
            cur=ListNode(val)
            if not head:
                head=cur
            if pre:
                pre.next=cur
            pre=cur
        
        if carry:
            pre.next=ListNode(carry)
        
        return head

 

posted on 2018-03-31 11:50  lina2014  阅读(152)  评论(0编辑  收藏  举报

导航