1. 程式人生 > >leetcode:2-Add Two Numbers

leetcode:2-Add Two Numbers

另一個 plan example num 提前 除了 += 指向 pre

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.

題意:給定兩個非空鏈表來表示兩個非負整數。 數字以相反的順序存儲,每個節點包含一個數字。 對這兩個數字加和並將其以鏈表形式返回。假定這兩個數字不包含任何前導零,除了數字0本身。

思路:若存在空鏈表,直接返回另一個即可。若均不為空,就對應位置逐個相加。註意,提前實例化一個存放結果鏈表的頭結點。

 1 class ListNode:
 2     def __init__(self,x):
3 self.val=x 4 self.next=None 5 6 class Solution: 7 def addTwoNumbers(self,l1,l2): 8 if l1 is None: #若存在空鏈表,直接返回另一個即可 9 return l2 10 elif l2 is None: 11 return l1 12 else: 13 carry = 0 #進位標誌 14 pNode = ListNode(0) #
存放結果的結點數值先放0 15 pHead = pNode #指向第一個元素的指針 16 while(l1 or l2): #直到某個表為空 17 sum = 0 #移動指針後先清空 18 if(l1): 19 sum = l1.val #sum存下l1當下指向的數 20 l1 = l1.next #存數後移動指針 21 if(l2): 22 sum += l2.val #sum進行對應位置加法運算 23 l2 = l2.next #存數後移動指針 24 sum += carry #加上進位 25 pHead.next = ListNode(sum%10) #存下當前位的數字 26 pHead = pHead.next #指向該數字 27 carry = (sum>=10) #表示進位 28 if(carry): #若結束l1和l2的遍歷仍有進位 29 pHead.next = ListNode(1) #記下進位 30 pHead = pNode.next #指向第一個位置 31 del pNode #刪除頭結點 32 return pHead 33 34 35 if __name__==__main__: 36 l1_1 = ListNode(2) 37 l1_2 = ListNode(4) 38 l1_3 = ListNode(3) 39 l1_1.next = l1_2 40 l1_2.next = l1_3 41 l2_1 = ListNode(5) 42 l2_2 = ListNode(6) 43 l2_3 = ListNode(4) 44 l2_1.next = l2_2 45 l2_2.next = l2_3 46 l3_1=Solution().addTwoNumbers(l1_1,l2_1) 47 while l3_1 != None: 48 print(l3_1.val) 49 l3_1 = l3_1.next

leetcode:2-Add Two Numbers