Question:
You are given two linked lists representing two non-negative numbers. the digits are stored in reverse order and each of their nodes contain a single digit. add the two numbers and return it as a linked list.
Input:(2-> 4-> 3) + (5-> 6-> 4)
Output:7-> 0-> 8
An1_1:
/*** 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) {// start typing your C/C ++ Solution Below if (L1 = NULL & L2 = NULL) {return NULL ;} listnode * retlist = new listnode (0); listnode * tmplist = retlist; listnode * head1 = L1; listnode * Head2 = L2; int carry = 0; while (head1! = NULL & head2! = NULL) {int sum = carry + head1-> Val + head2-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10 ); tmplist = tmplist-> next; head1 = head1-> next; head2 = head2-> next;} while (head1! = NULL) {int sum = carry + head1-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10); tmplist = tmplist-> next; head1 = head1-> next;} while (head2! = NULL) {int sum = carry + head2-> val; carry = sum/10; tmplist-> next = new listnode (sum % 10); tmplist = tmplist-> next; head2 = head2-> next;} If (carry = 1) {tmplist-> next = new listnode (1);} tmplist = retlist; retlist = retlist-> next; delete tmplist; return retlist ;}};
An1_2: