leetcode 2. Add Two Numbers
Question
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
问题
给定两个非空的链表,每个链表代表一个非负的整数。数字被逆序存放在链表里,每个链表节点代表一位数字。返回两数之和的链表。
除了0以为,每个数字的最高位不包含0。
分析
同步遍历并相加两个数字链表的节点即可,注意两个链表的长度可能不一致,以及进位的问题。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l3 = new ListNode(-1);
ListNode* pl3 = l3;
int carry = 0;
while (true)
{
int sum = carry;
if (l1 == NULL && l2 == NULL)
{
break;
}
if (l1 != NULL)
{
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL)
{
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
ListNode* tmp = new ListNode(sum % 10);
pl3->next = tmp;
pl3 = tmp;
}
if (carry != 0)
{
ListNode* tmp = new ListNode(carry);
pl3->next = tmp;
pl3 = tmp;
}
return l3->next;
}
};
总结
操作链表要注意链表尾的处理。