您的位置:首页 > 其它

题解——Leetcode 2. Add Two Numbers 难度:Medium

2017-04-28 11:07 706 查看
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. 两个整数逆序存储,低位向高位有进位时不再是向前而是向后进位。
2. 两个整数不一定有相同的位数,所以遍历链表时要判断是否遍历结束,如果结束,就将其相应位置为0。
3. 两个整数的最高位相加可能产生进位。
综上考虑,我们创建一个新的链表,其头节点为head,指向其的头指针为p,我们用carry表示对应位相加后的进位,sum表示相加后结果。
sum等于两个整数对应位相加再加上低位进位,sum向高位的进位carry = sum / 10,此时结果链表新增一个节点,其val = sum % 10即p->next = new ListNode(sum % 10)。这样便完成了一次加法和进位操作,结果链表和两个存储整数的链表的指针向后移动一位,重复之前的加法和进位操作,直到两个整数遍历结束且不存在进位。

/**
* 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 head(0), *p = &head;
int carry = 0;

while(l1 || l2 || carry){
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
p->next = new ListNode(sum % 10);

p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return head.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: