首页 > 技术文章 > 刷题练习记录(2)——两数相加(JAVA 和 Python)【链表】

anno-ymy 2018-12-24 14:56 原文

【2】两数相加

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

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

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

示例

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

【1】Java

【代码参考】

【1】【https://www.cnblogs.com/grandyang/p/4606334.html

    【http://www.cnblogs.com/grandyang/p/4129891.html

【2】【有测试代码】

    【https://www.cnblogs.com/lowseasonwind/p/9046843.html

======================================================

【Java单链表ListNode使用】

  【https://blog.csdn.net/superhero521/article/details/76573648

【关于(a=b?x:y)的使用】

  【https://zhidao.baidu.com/question/374801579.html

 

public class SolutionN2 {    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res=new ListNode(0);
        ListNode p=l1,q=l2,currrent=res;
        int carry=0;//进位
        while(p!=null||q!=null) {
            int x=(p!=null)?p.val:0;
            int y=(q!=null)?q.val:0;
            int sum=x+y+carry;
            carry=sum/10;
            currrent.next=new ListNode(sum%10);
            currrent=currrent.next;
            if(p!=null)
                p=p.next;
            if(q!=null)
                q=q.next;
        }
        if(carry>0) {
            currrent.next=new ListNode(carry);
        }
        
        return res.next;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

 

 

 

 

 

【2】Python

 【代码参考】

【1】【有测试代码】

    【https://blog.csdn.net/chenhua1125/article/details/80339751

====================================================================

 【2】关于python的单链表实现,已实践-参考【https://www.cnblogs.com/anno-ymy/p/11125969.html

 

 

 

class ListNode(object):
    def __init__(self,x):
        self.val=x
        self.next=None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :param l1:ListNode
        :param l2: ListNode
        :return: ListNode
        """
        carry=0
        res=ListNode(0)
        pre=res
        while l1 or l2 or carry:
            if l1:
                carry +=l1.val
                l1=l1.next
            if l2:
                carry +=l2.val
                l2=l2.next
            carry,val=divmod(carry,10)
            pre.next=ListNode(val)
            pre=pre.next
        return res.next

if __name__=='__main__':
    sol=Solution()

    l1=ListNode(2)
    l1.next=ListNode(4)
    l11=l1.next
    l11.next=ListNode(5)
    l12=l11.next

    l2=ListNode(5)
    l2.next=l21=ListNode(6)
    l21.next=l22=ListNode(4)

    res=sol.addTwoNumbers(l1,l2)

    while res:
        print (res.val)
        res=res.next

 

推荐阅读