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) + (4 -> 6 -> 4)
Output: 7-> 0 -> 7
Explanation: 342 + 464 = 806.
解题思路
两数之和,建立一个新链表,然后把输入的两个链表从头往后遍历,每两个相加,添加一个新节点到新链表后面。
C++代码实现
class Numbers {
public:
ListNode* addTwoNumbers(ListNode* L1, ListNode* L2) {
ListNode *d = new ListNode(-1), *p = d;建立一个d结点,将两个结点相加生成的新结点按顺序加到d结点之后
int c= 0;//表示上进位
while (L1 || L2) {
//判断结点是否为空,若为空则取0,否则取结点值。
int list1 = L1 ? L1->elem: 0;
int list2 = L2 ? L2->elem: 0;
int sum = list1 + list2 + c;
c = sum / 10;//更新c
p->next = new ListNode(sum % 10);//以 sum%10 为值建立一个新结点,连到c后面,然后c移动到下一个结点
p= p->next;
if (L1) L1 = L1->next;//更新两个结点,若存在,则指向下一个位置
if (L2) L2 = L2->next;
}
//while循环退出之后,最高位的进位问题要最后特殊处理一下,若c为1,则再建一个值为1的结点.
if (c) p>next = new ListNode(1);
return d->next;
}
};