题目
Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
标签
Linked List、Math
难度
中等
分析
题目意思是给定两个链表A、B,逐个节点相加,返回元素和的链表,10进一。做法是逐个将链表A和链表B的元素相加,并覆盖原来链表A/B位置上的值,注意当某个链表到达末尾的时候,要考虑之前的运算是否有进位。
C代码实现
void addNodeToList(struct ListNode* list)
{
struct ListNode * node = (struct ListNode *)malloc(sizeof(struct ListNode));
if(node)
{
node->val = 1;
node->next = NULL;
list->next = node;
}
}
void addTailNodeToList(struct ListNode* list, bool fgADD)
{
struct ListNode* temp;
while(list)
{
if(true == fgADD)
{
list->val = list->val + 1;
fgADD = false;
if(list->val >= 10)
{
list->val = list->val - 10;
fgADD = true;
}
else
fgADD = false;
temp = list;
list = list->next;
if(!list)
{
if(fgADD==true)
addNodeToList(temp);
return;
}
}
else
return;
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
bool fgADD = false;
struct ListNode *l1_head, *l2_head;
struct ListNode *last_point;
if(!l1) return l2;
if(!l2) return l1;
l1_head = l1; l2_head = l2;
while(l1 && l2)
{
if(true == fgADD)
l1->val = l2->val = l1->val + l2->val + 1;
else
l1->val = l2->val = l1->val + l2->val;
if(l1->val >= 10)
{
l1->val = l2->val = l1->val - 10;
fgADD = true;
}
else
fgADD = false;
last_point = l1; // remember the last node
l1 = l1->next;
l2 = l2->next;
}
if(l1)
{
addTailNodeToList(l1, fgADD);
return l1_head;
}
if(l2)
{
addTailNodeToList(l2, fgADD);
return l2_head;
}
if(true == fgADD)
addNodeToList(last_point);
return l1_head;
}