给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//头插法
void headInsert(ListNode*& head, int val)
{
ListNode* node = new ListNode(0);
node->val = val;
node->next = NULL;
if (head == NULL) //链表为空
{
head = node;
}
else
{
node->next = head;
head = node;
}
}
//尾插法
void tailInsert(ListNode*& head, int val,ListNode*& tail)
{
ListNode* node = new ListNode(0);
node->val = val;
node->next = NULL;
if (head == NULL) //链表为空 头尾都为同一节点
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = NULL; //返回链表的头指针
ListNode* tail = NULL; //链表的尾节点
int bit = 0; //是否进位
ListNode* l1Cur = l1;
ListNode* l2Cur = l2;
int curVal;
while (l1Cur && l2Cur)
{
curVal = l1Cur->val + l2Cur->val + bit;
bit = curVal / 10;
// headInsert(head, curVal % 10);
tailInsert(head, curVal % 10,tail);
l1Cur = l1Cur->next;
l2Cur = l2Cur->next;
}
while (l1Cur)
{
curVal = l1Cur->val + bit;
bit = curVal / 10;
// headInsert(head, curVal % 10);
tailInsert(head, curVal % 10, tail);
l1Cur = l1Cur->next;
}
while (l2Cur)
{
curVal = l2Cur->val + bit;
bit = curVal / 10;
// headInsert(head, curVal % 10);
tailInsert(head, curVal % 10, tail);
l2Cur = l2Cur->next;
}
if (bit > 0)
{
// headInsert(head, bit);
tailInsert(head, bit, tail);
}
return head;
}
int main()
{
ListNode* l1 = NULL;
headInsert(l1, 3);
headInsert(l1, 4);
headInsert(l1, 2);
ListNode* l2 = NULL;
headInsert(l2, 4);
headInsert(l2, 6);
headInsert(l2, 5);
ListNode*head = addTwoNumbers(l1,l2);
while (head)
{
cout << head->val << endl;
head = head->next;
}
system("pause");
return 0;
}