Add Two Numbers算法题,c++实现:
#include<iostream>
using namespace std;
class Solution
{
public:
ListNode * addTwoNumbers(ListNode * l1, ListNode * l2);
};
ListNode * Solution::addTwoNumbers(ListNode * l1, ListNode * l2)
{
ListNode * root = new ListNode(1);
if(root == NULL)
{
cout << "Memory Location Error ! " << endl;
return NULL;
}
else
{
ListNode * p1 = l1;
ListNode * p2 = l2;
ListNode * p_cur = root;
int jinwei = 0;
while(p1 != NULL && p2 != NULL)
{
int value = p1->val + p2->val + jinwei;
ListNode * p = new ListNode(value % 10);
jinwei = value / 10;
p->next = NULL;
p_cur->next = p;
p_cur = p;
p1 = p1->next;
p2 = p2->next;
}
if(p1 == NULL && p2 != NULL)
{
while(p2 != NULL)
{
int value = p2->val + jinwei;
ListNode * p = new ListNode(value % 10);
jinwei = value / 10;
p_cur->next = p;
p_cur = p;
p2 = p2->next;
}
if(jinwei != 0)
{
ListNode * p = new ListNode(jinwei);
p_cur->next = p;
}
}
else if(p2 == NULL && p1 != NULL)
{
while(p1 != NULL)
{
int value = p1->val + jinwei;
ListNode * p = new ListNode(value % 10);
jinwei = value / 10;
p_cur->next = p;
p_cur = p;
p1 = p1->next;
}
if(jinwei != 0)
{
ListNode * p = new ListNode(jinwei);
p_cur->next = p;
}
}
else if(p1 == NULL && p2 == NULL)
{
if(jinwei != 0)
{
ListNode * p = new ListNode(jinwei);
p_cur->next = p;
}
}
}
return root->next;
}
ListNode * CreateList(int size)
{
if(size == 0)
return NULL;
else
{
cout << "please enter the value : " << endl;
int value;
cin >> value;
ListNode * p = new ListNode(value);
if(p == NULL)
{
cout << "Memory Location Error ! " << endl;
return NULL;
}
else
{
p->next = CreateList(size - 1);
return p;
}
}
}
void ListPrint(ListNode * l)
{
ListNode * p = l;
while(p != NULL)
{
cout << p->val << endl;
p = p->next;
}
return;
}
int main(int argc, char ** argv)
{
cout << "please enter the number of nodes in list1 : " << endl;
int size1;
cin >> size1;
ListNode * l1 = CreateList(size1);
//ListPrint(l1);
cout << "please enter the number of nodes in list2 : " << endl;
int size2;
cin >> size2;
ListNode * l2 = CreateList(size2);
Solution solution = Solution();
ListNode * result = solution.addTwoNumbers(l1, l2);
ListPrint(result);
}