/**
* 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) {
ListNode* res;
ListNode* p1=l1;
ListNode* p2=l2;
ListNode* head = new ListNode(0);
ListNode* temp = head;
int jin = 0;
head->val = p1->val + p2->val;
if(p1->val + p2->val >=10){
jin = 1;
head->val = p1->val + p2->val - 10;
}
p1 = p1->next;
p2 = p2->next;
while(p1 != NULL && p2!=NULL){
ListNode* link = new ListNode(0);
temp->next = link;
if(p1->val + p2->val + jin<10){
link->val = p1->val + p2->val + jin;
cout<<link->val<<endl;
jin = 0;
}
else{
link->val = p1->val + p2->val + jin - 10;
jin = 1;
}
p1 = p1->next;
p2 = p2->next;
temp = link;
}
if(jin == 1){
if(p1 == NULL && p2 ==NULL){
ListNode* link = new ListNode(0);
link->val = 1;
temp->next = link;
temp = link;
return head;
}
if(p1 == NULL && p2!= NULL){
while(p2!=NULL ){
ListNode* link = new ListNode(0);
if(p2->val + jin >=10){
link->val = p2->val + jin - 10;
jin = 1;
temp->next = link;
temp = link;
p2 = p2->next;
}
else{
link->val = p2->val + jin;
jin = 0;
temp->next = link;
temp = link;
p2 = p2->next;
}
}
if(jin == 1){
ListNode* link = new ListNode(0);
link->val = jin;
temp->next = link;
temp = link;
}
return head;
}
if(p1 != NULL && p2 == NULL){
while(p1 != NULL){
ListNode* link = new ListNode(0);
if(p1->val + jin >=10){
link->val = p1->val + jin - 10;
jin = 1;
temp->next = link;
temp = link;
p1 = p1->next;
}
else{
link->val = p1->val + jin;
jin = 0;
temp->next = link;
temp = link;
p1 = p1->next;
}
}
if(jin == 1){
ListNode* link = new ListNode(0);
link->val = jin;
temp->next = link;
temp = link;
}
return head;
}
}
else{
if(p1==NULL &&p2==NULL){
return head;
}
if(p1!=NULL && p2==NULL){
temp->next = p1;
return head;
}
if(p2!=NULL && p1==NULL){
temp->next = p2;
return head;
}
}
}
};
/**
* 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) {
if(l1->val == 0 && l1->next == NULL){
return l2;
}
else if(l2->val == 0 && l2->next == NULL){
return l1;
}
else{
ListNode * head = NULL;
ListNode * pre = NULL;
int add = 0;
int sum = 0;
bool flag_l1 = true;
bool flag_l2 = true;
while(true){
if ((flag_l1 == false) && (flag_l2 == false) && add == 0){
break;
}
sum = add;
if(flag_l1){
sum += l1->val;
}
if(flag_l2){
sum += l2->val;
}
if (sum >= 10){
sum = sum % 10;
add = 1;
}
else{
add = 0;
}
if(head == NULL){
head = new ListNode(sum);
pre = head;
}
else{
ListNode * p = new ListNode(sum);
pre->next = p;
pre = pre->next;
}
if(l1->next != NULL){
l1 = l1->next;
}
else{
flag_l1 = false;
}
if(l2->next != NULL){
l2 = l2->next;
}
else{
flag_l2 = false;
}
}
return head;
}
}
};