题目:
LeetCode:2. Add Two Numbers
描述:
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
分析:
- 思路如下:
1) 遍历两个链表,两结点值加上上一链表的进位,作为新节点的val值;
2) 还有一种想法是,把链表提取成unsigned long 整数来做,从整数创建一个新的链表;2 -> 4 -> 3 ==>342
显而易见,第一种方向更为合理一些。
代码:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* listHead = NULL;
ListNode* listEnd = listHead;
int nSum = 0;
while (NULL != l1 || NULL != l2)
{
nSum = nSum / 10;
// 1、不为空则添加l1结点数
if (NULL != l1)
{
nSum += l1->val;
l1 = l1->next;
}
// 2、不为空则添加l2结点数
if (NULL != l2)
{
nSum += l2->val;
l2 = l2->next;
}
// 3、添加结点,移动链表指针至最末端
ListNode* listTemp = new ListNode(nSum % 10);
if (NULL != listHead)
{
listEnd->next = listTemp;
}
else
{
listHead = listTemp;
}
listEnd = listTemp;
}
// 执行完加法后,最后一位进位
if (nSum > 9)
{
listEnd->next = new ListNode(nSum / 10);
}
return listHead;
}
备注:
修改前的代码:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* listHead = new ListNode(0);
ListNode* listEnd = listHead;
int nSum = 0;
while (NULL != l1 || NULL != l2)
{
nSum = nSum / 10;
// 1、不为空则添加l1结点数
if (NULL != l1)
{
nSum += l1->val;
l1 = l1->next;
}
// 2、不为空则添加l2结点数
if (NULL != l2)
{
nSum += l2->val;
l2 = l2->next;
}
// 3、添加结点,移动链表指针至最末端
ListNode* listTemp = new ListNode(nSum % 10);
listEnd->next = listTemp;
listEnd = listTemp;
}
// 执行完加法后,最后一位进位
if (nSum > 9)
{
listEnd->next = new ListNode(nSum / 10);
}
// 处理head指针的内存释放
listEnd = listHead;
listHead = listHead->next;
delete listEnd;
listEnd = NULL;
return listHead;
}
拜读了Edward Desire的 Add Two Numbers 以及小伙伴JeffLai的代码。
修改前的代码效率会更高一些,JeffLai的可以达到39ms,等详细时间在做好好的探究。