1. 程式人生 > >LeetCode第二題:兩數相加(addTwoNumbers)的Python3實現。

LeetCode第二題:兩數相加(addTwoNumbers)的Python3實現。

題目描述:

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.

題目分析:

這道題不難,但是有三點需要注意,尤其是第三點:

  1. 連結串列對應結點相加時增加前一個結點的進位,並儲存下一個結點的進位;
  2. 兩個連結串列長度不一致時,要處理較長連結串列剩餘的高位和進位計算的值,例如:23+320=343;
  3. 如果最高位計算時還產生進位,則還需要新增一個額外結點,例如:5+5=10。

這道題我使用Python3來解決。Python與C++或者C語言不一樣:它沒有指標,所以不能通過指標來對同一個地址進行操作。因此,我不能像C++一樣利用指標建立一個連結串列,而是隻能建立一個list,每做完一位加法,就生成一個新的ListNode,並將這個新的ListNode與前面一個ListNode的next關聯起來:result[-2].next=result[-1](下面程式碼中標黑部分)。這段程式碼比較冗長,但是時間複雜度是o(n)。

程式碼:

def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        jinwei=0
        result=[]
        count=0
        while l1!=None and l2!=None:
        sum=l1.val+l2.val+jinwei
        if sum>9:
        result.append(ListNode(sum-10))
        jinwei=1
        else:
        result.append(ListNode(sum))
        jinwei=0
        l1=l1.next
        l2=l2.next
        if count!=0: #第一次是兩個數個位相加,result列表中只有一個元素,所以不需要執行下面這條語句
        result[-2].next=result[-1]


        count=1

        while l1!=None:
        sum=l1.val+jinwei
        if sum>9:
        result.append(ListNode(sum-10))
        jinwei=1
        else:
        result.append(ListNode(sum))
        jinwei=0
        l1=l1.next
        result[-2].next=result[-1]

        while l2!=None:
        sum=l2.val+jinwei
        if sum>9:
        result.append(ListNode(sum-10))
        jinwei=1
        else:
        result.append(ListNode(sum))
        jinwei=0
        l2=l2.next
        result[-2].next=result[-1]

        if jinwei==1:
        result[-1].next=ListNode(jinwei)
        return result[0]