title :
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
code : OJ Test via runtime:171 ms
1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8 #@return a ListNode9 defaddtwonumbers (self, L1, L2):Ten ifL1 isNone: One returnL2 A ifL2 isNone: - returnL1 - theDummyhead =listnode (0) -p =listnode (0) -Dummyhead.next =P - +Jinwei =0 - whileL1 is notNone andL2 is notNone: +Curr_total = l1.val + L2.val +Jinwei AL1 =L1.next atL2 =L2.next -Curr_digit = curr_total% 10 -Jinwei = CURR_TOTAL/10 -Curr_node =ListNode (curr_digit) -P.next =Curr_node -p =P.next in - ifL1 is notNone: to whileL1 is notNone: +Curr_total = L1.val +Jinwei -L1 =L1.next theCurr_digit = curr_total% 10 *Jinwei = CURR_TOTAL/10 $Curr_node =ListNode (curr_digit)Panax NotoginsengP.next =Curr_node -p =P.next the ifL2 is notNone: + whileL2 is notNone: ACurr_total = L2.val +Jinwei theL2 =L2.next +Curr_digit = curr_total% 10 -Jinwei = CURR_TOTAL/10 $Curr_node =ListNode (curr_digit) $P.next =Curr_node -p =P.next - the ifJinwei = = 1: -Curr_node = ListNode (1)WuyiP.next =Curr_node the - returnDummyhead.next.next
Ideas :
It's the addition operation. Note that all values on the two-linked list have a carry after calculation, and if there is a carry, it needs to be processed.
Leetcode "Add Numbers" Python implementation