[Leetcode题解] 2 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
题目传送门:Add Two Numbers
思路
这道题主要是考察对链表的操作,难度不大。一般合并两个链表都遵循如下的代码结构:
while(l1 && l2)
{
...
}
while(l1)
{
...
}
wile(l2)
{
...
}
这道题目需要考虑如果两个链表结点相加之和大于10,需要向前一位进1。因此需要用个变量pre
保存前一个的进位。每次计算两数之和应该为int tmp = l1->val + l2->val + pre
。由于两个数相加不可能超过20,所以只需要考虑tmp
是否超过10。超过的话tmp -= 10; pre = 1
,否则tmp
不变,pre = 0
。
要注意的是,在l1,l2都遍历完之后,仍需要考虑最后一位是否进位,即如果pre != 0
,那么新建一个结点,值为pre
,并链在链表最后。
解法
代码如下所示:
struct ListNode * addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode * head, * current;
int pre = 0;
head = (struct ListNode *)malloc(sizeof(struct ListNode));
current = head;
while(l1 && l2)
{
struct ListNode * l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
int tmp = l1->val + l2->val + pre;
if(tmp >= 10)
{
l3->val = tmp - 10;
l3->next = NULL;
pre = 1;
}
else
{
l3->val = tmp;
l3->next = NULL;
pre = 0;
}
current->next = l3;
current = current->next;
l1 = l1->next;
l2 = l2->next;
}
while(l1)
{
struct ListNode * l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
int tmp = l1->val + pre;
if(tmp >= 10)
{
l3->val = tmp - 10;
l3->next = NULL;
pre = 1;
}
else
{
l3->val = tmp;
l3->next = NULL;
pre = 0;
}
current->next = l3;
current = current->next;
l1 = l1->next;
}
while(l2)
{
struct ListNode * l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
int tmp = l2->val + pre;
if(tmp >= 10)
{
l3->val = tmp - 10;
l3->next = NULL;
pre = 1;
}
else
{
l3->val = tmp;
l3->next = NULL;
pre = 0;
}
current->next = l3;
current = current->next;
l2 = l2->next;
}
if(pre)
{
struct ListNode * l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
l3->val = pre;
l3->next = NULL;
current->next = l3;
current = current->next;
}
return head->next;
}