问题描述
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
笔记
在代码2中,要注意的时判断l1和l2是否到了尽头。
if (l1 != NULL)
l1 = l1->next;
if (l2 != NULL)
l2 = l2->next;
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
int carry = 0;
ListNode *pre = new ListNode(0);
ListNode *tmp = pre;
while (l1 != NULL && l2 != NULL)
{
int num = l1->val + l2->val + carry;
l1 = l1->next;
l2 = l2->next;
tmp -> next = new ListNode(num % 10);
tmp = tmp -> next;
carry = num / 10;
}
while (l1 != NULL)
{
int num = l1->val + carry;
l1 = l1->next;
tmp -> next = new ListNode(num % 10);
tmp = tmp -> next;
carry = num / 10;
}
while (l2 != NULL)
{
int num = l2->val + carry;
l2 = l2->next;
tmp -> next = new ListNode(num % 10);
tmp = tmp -> next;
carry = num / 10;
}
if (carry == 1)
{
tmp->next = new ListNode(1);
tmp = tmp->next;
}
tmp->next = NULL;
return pre->next;
}
};
第二次写。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *beforeHead = new ListNode(0);
ListNode *pre = beforeHead;
int carry = 0;
while (l1 != NULL || l2 != NULL)
{
int v1 = (l1 == NULL) ? 0 : l1->val;
int v2 = (l2 == NULL) ? 0 : l2->val;
int tmp = v1 + v2 + carry;
ListNode *now = new ListNode(tmp%10);
carry = tmp / 10;
pre->next = now;
pre = now;
if (l1 != NULL)
l1 = l1->next;
if (l2 != NULL)
l2 = l2->next;
}
if (carry)
{
ListNode *now = new ListNode(1);
pre->next = now;
pre = now;
}
pre->next = NULL;
return beforeHead->next;
}
};