您的位置:首页 > 其它

算法 - 两个链表中数字相加

2018-02-03 14:52 375 查看
要求:

有两个int行的整数,分别保存在两个非空的LinkList,每个元素中只保存int值的一位数字。

现在要求将两个LinkList中的每个元素依次相加,返回一个新的LinkList,并且将新的LinkList中每个元素去除依次打印出来的结果与原先两个整数相加的值相同。

例子:

输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 0 8.


主要实现:

#include<Windows.h>
#include<iostream>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int addFactor = 0;
ListNode *headListNode = new ListNode(0);
ListNode *tmpListNode = headListNode;

if (l1 == NULL || l2 == NULL)
{
throw new invalid_argument("invalid argument");
}

while (1)
{

int value1 = l1->val;
int value2 = l2->val;
int sum = value1 + value2 + addFactor;
addFactor = 0;

if (sum > 9)
{
addFactor = sum / 10;
sum = sum % 10;
}

tmpListNode->val = sum;

if (l1->next == NULL && l2->next == NULL)
{
             if(addFactor > 0)
{
ListNode *nextListNode = new ListNode(0);
nextListNode->val = addFactor;

tmpListNode-> next = nextListNode;
}
break;
}
else
{
ListNode *nextListNode = new ListNode(0);
if (l1->next != NULL)
l1 = l1->next;
else
l1->val = 0;

if (l2->next != NULL)
l2 = l2->next;
else
l2->val = 0;

tmpListNode-> next = nextListNode;
tmpListNode = nextListNode;
}

}

return headListNode;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Add Two Numbers