2.两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

C#代码:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
         ListNode total=new ListNode(0),current=total;//current 和total指向同一地址
         int x,y,num;
         int decade=0;
        
         while(l1!=null||l2!=null)
         {
             x=l1!=null?l1.val:0;
             y=l2!=null?l2.val:0;
             num=(x+y+decade)%10;
             decade=(x+y+decade)/10;
             current.next=new ListNode(num);     //current和total都具有指向current.next的地址
             l1=l1==null?null:l1.next;
             l2=l2!=null?l2.next:null;
             current=current.next;               //current地址变为了current.next的地址,total不变
         }
         if(decade==1)
         {
             current.next=new ListNode(decade);
         }
         return total.next;                     //将total地址改为指向第二个
    }    
}

Python代码:

# 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
        """
        total=ListNode(0)
        current=total
        decade=0
        while(l1 or l2):
       
            x=l1.val if l1 else 0
            y=l2.val if l2 else 0
            num=(x+y+decade)%10
            decade=(x+y+decade)/10
            current.next=ListNode(num)
            l1=l1.next if l1 else None
            l2=l2.next if l2 else None
            current=current.next
       
        if(decade==1):
           current.next=ListNode(decade) 
        
        return total.next
        

 





posted on 2018-12-22 15:38  明君  阅读(159)  评论(0编辑  收藏  举报

导航