#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cstring>
#include <assert.h>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
ListNode* sumList = new ListNode(0);
sumList->next = NULL;
if(l1->next == NULL){
sumList = l2;
}else if(l2->next == NULL){
sumList = l1;
}else{
int add = 0; //进位
int sum = 0; //余数
ListNode* p = l1->next;
ListNode* q = l2->next;
ListNode* n = sumList;
while(p != NULL || q != NULL){
if(p != NULL && q != NULL){ //等长
sum = p->val + q->val + add;
if(sum > 9){
add = 1;
sum = sum - 10;
}else{
add = 0;
}
ListNode* pNewNode = new ListNode(0);
pNewNode->val = sum;
pNewNode->next = NULL;
n->next = pNewNode;
n = pNewNode;
q = q->next;
p = p->next;
}else if(p == NULL){ // q长
sum = q->val + add;
if(sum > 9){
add = 1;
sum = sum - 10;
}else{
add = 0;
}
ListNode* pNewNode = new ListNode(0);
pNewNode->val = sum;
pNewNode->next = NULL;
n->next = pNewNode;
n = pNewNode;
q = q->next;
}else{ //p长
sum = p->val + add;
if(sum > 9){
add = 1;
sum = sum - 10;
}else{
add = 0;
}
ListNode* pNewNode = new ListNode(0);
pNewNode->val = sum;
pNewNode->next = NULL;
n->next = pNewNode;
n = pNewNode;
p = p->next;
}
}
//最后一个节点 > 10
if(add == 1){
ListNode* pNewNode = new ListNode(0);
pNewNode->val = add;
pNewNode->next = NULL;
n->next = pNextNode;
n = pNewNode;
}
}
return sumList;
}
void createList(ListNode* pHead, vector<int> data){
ListNode* p = pHead;
vector<int>::iterator itr;
if(data.size() == 0){
return;
}else{
for(itr = data.begin(); itr != data.end(); itr++){
ListNode* pNewNode = new ListNode(0);
pNewNode->val = *itr;
pNewNode->next = NULL;
p->next = pNewNode;
p = pNewNode;
}
}
}
void destroyList(ListNode* pHead){
assert(pHead != NULL);
ListNode* pNext = pHead->next;
while(pNext != NULL){
delete pHead;
pHead = pNext;
pNext = pHead->next;
}
delete pHead;
pHead = NULL;
return;
}
void displayList(listNode* pHead){
ListNode *p = pHead;
while(p->next != NULL){
cout << p->next->val << ",";
p = p->next;
}
cout << endl;
}
int main(){
vector<int> data1{2, 4, 3};
vector<int> data2{5, 6, 4};
ListNode* list1 = NULL;
list1 = new ListNode(0);
list1->next = NULL;
createList(list1, data1);
ListNode* list2 = NULL;
list2 = new ListNode(0);
list2->next = NULL;
createList(list2, data2);
ListNode* list3 = addTwoNumbers(list1, list2);
displayList(list3);
destroyList(list1);
destroyList(list2);
destroyList(list3);
return 0;
}