1. 程式人生 > >刷題練習記錄(2)——兩數相加(JAVA 和 Python)【連結串列】

刷題練習記錄(2)——兩數相加(JAVA 和 Python)【連結串列】

【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

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

 

 

 

 

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