题目
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
Explanation: 342 + 465 = 807.
思路分析
没啥好说的,指针操作,水题。时间太晚了,一边看S9一边写,效率低下。
我的代码
/**
* 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) {
int len_1 = 0, len_2 = 0;
ListNode *r1 = l1, *r2 = l2, *l3 = new ListNode(-1), *r3 = l3;;
int former = 0, x1, x2;
while (r1 != NULL || r2 != NULL) {
x1 = r1 == NULL ? 0 : r1->val;
x2 = r2 == NULL ? 0 : r2->val;
l3->val = (x1 + x2 + former) % 10;
former = int((x1 + x2 + former) / 10);
ListNode *l3_next = new ListNode(-1);
l3->next = l3_next;
l3 = l3->next;
if (r1)
r1 = r1->next;
if (r2)
r2 = r2->next;
}
if (former) {
l3->val = former;
}
l3 = r3;
while (r3 != NULL) {
if (r3->next != NULL && r3->next->val == -1) {
r3->next = NULL;
break;
}
r3 = r3->next;
}
return l3;
}
};