Add Two NumbersNov
1 '11
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
Note: 不知道大家是不是都看懂题目了,我就看了好久!就例子来说,其实就是342 + 465 = 807,但是是用链表倒序存储的。看懂题目之后,做起来就比较简单了,唯一需要注意的地方就是“进位”的问题!
代码如下:
ListNode *addTwoNumbers(ListNode *first, ListNode *second)
{
int carry = 0; // 进位
ListNode* pHead = NULL;
ListNode* pTail = NULL;
while (first && second)
{
int x = first->val + second->val + carry;
ListNode* pNext = new ListNode(x%10);
carry = x/10;
if (!pHead)
{
pHead = pNext;
pTail = pNext;
}
else
{
pTail->next = pNext;
pTail = pNext;
}
first = first->next;
second = second->next;
}
while (second)
{
int x = second->val + carry;
carry = x/10;
ListNode* pNext = new ListNode(x%10);
if (!pHead)
{
pHead = pNext;
pTail = pNext;
}
else
{
pTail->next = pNext;
pTail = pNext;
}
second = second->next;
}
while (first)
{
int x = first->val + carry;
carry = x/10;
ListNode* pNext = new ListNode(x%10);
if (!pHead)
{
pHead = pNext;
pTail = pNext;
}
else
{
pTail->next = pNext;
pTail = pNext;
}
first = first->next;
}
if (carry)
{
ListNode* pNext = new ListNode(carry);
pTail->next = pNext;
pTail = pNext;
}
return pHead;
}
本文介绍了一种使用链表实现加法的方法,输入为两个非负数的链表表示,链表中的数字按逆序存储。文章详细解释了如何处理进位问题,并提供了完整的代码示例。
513

被折叠的 条评论
为什么被折叠?



