/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ void makell(ListNode* head, int value) { ListNode* p=new ListNode(); p->val=value; p->next=NULL; ListNode* l=head; while((l->next!=NULL)&&(l!=NULL)) { l=l->next; } l->next=p; } class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* head=new ListNode(); head->val=0; head->next=NULL; ListNode* i1 = l1; ListNode* i2 = l2; int c=0; while(i1!=NULL||i2!=NULL) { int d1,d2; if(i1==NULL&&i2==NULL) break; if(i1==NULL) d1=0; else { d1=i1->val; i1=i1->next; } if(i2==NULL) d2=0; else { d2=i2->val; i2=i2->next; } int p=d1+d2+c; int r=p%10; makell(head,r); c=p/10; } if(c!=0) { makell(head,c); } return head->next; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter