#2. ADD Numbers
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
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode* head=NewListNode (0); ListNode* p=Head; ListNode* q=Head; intcarry=0; intsum=0; intAll=0; while(l1!=null&&l2!=NULL) { All=l1->val+l2->val+carry; Sum=all%Ten; Carry=all/Ten; P->val=sum; P->next=NewListNode (0); P=p->Next; L1=l1->Next; L2=l2->Next; } while(l1!=NULL) { All=l1->val+carry; Sum=all%Ten; Carry=all/Ten; P->val=sum; P->next=NewListNode (0); P=p->Next; L1=l1->Next; } while(l2!=NULL) { All=l2->val+carry; Sum=all%Ten; Carry=all/Ten; P->val=sum; P->next=NewListNode (0); P=p->Next; L2=l2->Next; } if(carry!=0) {p->val=1; P->next=NewListNode (0); P=p->Next; } while(q!=NULL) { if(q->next->next==NULL) {Q->next=NULL; Break; } q=q->Next; } returnHead; }};
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode* head=NewListNode (0); ListNode* p=Head; intcarry=0; intsum=0; intAll=0; while(l1!=null&&l2!=NULL) { All=l1->val+l2->val+carry; Sum=all%Ten; Carry=all/Ten; P->next=Newlistnode (sum); P=p->Next; L1=l1->Next; L2=l2->Next; } while(l1!=NULL) { All=l1->val+carry; Sum=all%Ten; Carry=all/Ten; P->next=Newlistnode (sum); P=p->Next; L1=l1->Next; } while(l2!=NULL) { All=l2->val+carry; Sum=all%Ten; Carry=all/Ten; P->next=Newlistnode (sum); P=p->Next; L2=l2->Next; } if(carry!=0) {p->next=NewListNode (1); P=p->Next; } returnHead->Next; }};
Leetcode-2 ADD Numbers