Leetcode 2. Add Two Numbers
https://leetcode.com/problems/add-two-numbers/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { /* 可能长度+1,l1为返回答案.[假设l1,l2结构不需要了] */ ListNode *ll1=l1,*ll2=l2; int a=ll1->val,b=ll2->val; ll1->val=(a+b)%10; int carry_bit=(a+b)/10;//进位 while(ll1->next && ll2->next){ /* 10进制加法,直到某一个列表到末尾,相加后结束. */ a=ll1->next->val,b=ll2->next->val; ll1->next->val=(a+b+carry_bit)%10; carry_bit=(a+b+carry_bit)/10; ll1=ll1->next; ListNode *tmp=ll2; ll2=ll2->next; delete tmp; } if(ll2->next) ll1->next=ll2->next;//ll1设为长链 while(ll1->next && carry_bit){ /* 进位的处理 */ a=ll1->next->val; ll1->next->val=(a+carry_bit)%10; carry_bit=(a+carry_bit)/10; ll1=ll1->next; } if(carry_bit==1){ /* 长度+1的情况 */ ListNode* p=new ListNode(1); ll1->next=p; } return l1; } };
python版本
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: p=l1 e=0 x=l1.val+l2.val+e e=x//10 l1.val=x%10 while l1.next and l2.next: x=l1.next.val+l2.next.val+e e=x//10 l1.next.val=x%10 l1=l1.next l2=l2.next if l2.next: l1.next=l2.next while l1.next: x=l1.next.val+e e=x//10 l1.next.val=x%10 l1=l1.next if e!=0: x=ListNode(e) l1.next=x return p