1.问题:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Figure 1. Visualization of the addition of two numbers: 342+465=807.
Each node contains a single digit and the digits are stored in reverse order.
2 方法: [ me ]
思想: 两条链表节点数目不一样, a表节点多, b表节点少, len(a)-len(b) = n, 那么假想给b“添加”n个节点,节点中的值都为0。 此时,a表和b表长度相同了,对应节点一次增加(注意进位), 到最高位相加(最后一位相加)时,需要判断 相加之和是否 大于10,大于10则需要进位。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
int overflow = 0;
// 两条链表,以节点多的链表为基础。为 节点少的链表 填充val=0 .
while(l1 || l2)
{
int one = (l1 == NULL) ? 0: l1->val;
int two = (l2 == NULL) ? 0: l2->val;
int node_result = -1;
int sum = one + two + overflow;
node_result = sum %10;
overflow = sum /10;
struct ListNode* newnode = (struct ListNode* )malloc(sizeof(struct ListNode));
if (NULL == newnode)
{
printf("malloc error");
}
// insert into list
newnode->val = node_result;
newnode->next = NULL;
if (NULL == head)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
// update index
l1 = (l1==NULL)?NULL:l1->next;
l2 = (l2==NULL)?NULL:l2->next;
}
// 最后两个数相加的最高位是否为1
if (1 == overflow)
{
struct ListNode* newnode = (struct ListNode* )malloc(sizeof(struct ListNode));
if (NULL == newnode)
{
printf("malloc error");
}
newnode->val = overflow;
newnode->next = NULL;
tail->next = newnode;
}
/* 优化。 "最后两个数相加最高位是否为1" 可以放入while循环中
while(l1 || l2 || overflow)
{
int one = (l1 == NULL) ? 0: l1->val;
int two = (l2 == NULL) ? 0: l2->val;
int node_result = -1;
int sum = one + two + overflow;
node_result = sum %10;
overflow = sum /10;
struct ListNode* newnode = (struct ListNode* )malloc(sizeof(struct ListNode));
if (NULL == newnode)
{
printf("malloc error");
}
// insert into list
newnode->val = node_result;
newnode->next = NULL;
if (NULL == head)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
// update index
l1 = (l1==NULL)?NULL:l1->next;
l2 = (l2==NULL)?NULL:l2->next;
}
*/
return head;
}