# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Plus: def plusAB(self, a, b): # write code here s=ListNode(0) h=s c=0 while a!=None or b!=None: s.next=ListNode(0) s=s.next if a==None: na=0 else: na=a.val a=a.next if b==None: nb=0 else: nb=b.val b=b.next s.val=(na+nb+c)%10#要考虑进位 c=int((na+nb+c)/10) if c>0: s.next=ListNode(0) s=s.next s.val=c return h.next
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class Plus { public: ListNode* plusAB(ListNode* a, ListNode* b) { // write code here ListNode* Head=new ListNode(-1); ListNode* p=Head; ListNode* node=nullptr; int c=0,sum,val_a,val_b; ListNode* pa=a,*pb=b; while(pa!=nullptr || pb!=nullptr || c!=0){ val_a=(pa==nullptr?0:pa->val); val_b=(pb==nullptr?0:pb->val); sum=val_a+val_b+c; c=sum/10; node=new ListNode(sum%10); p->next=node; p=node; pa=(pa==nullptr?nullptr:pa->next); pb=(pb==nullptr?nullptr:pb->next); } return Head->next; } };