Add Two Numbers
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
思路
类似于高精度加法,只不过是用链表实现。我比较懒,只想写这么多。
代码
/**
* 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 *ret = new ListNode(0);
ListNode *head = ret;
int extra = 0;
int ans = 0;
while (l1 != NULL || l2 != NULL) {
if (l1 != NULL) {
ans += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
ans += l2->val;
l2 = l2->next;
}
ans += extra;
extra = ans/10;
ans %= 10;
ListNode *node = new ListNode(ans);
head->next = node;
head = node;
ans = 0;
}
if (extra != 0) {
ListNode *node = new ListNode(extra);
head->next = node;
head = node;
}
return ret->next;
}
};