兩個非負整數以**逆序**鏈表存儲 (個位在頭),逐位相加返回結果鏈表 (亦逆序)。
例:(2→4→3) + (5→6→4) = 342 + 465 = 807 → (7→0→8)
// C++
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0), *tail = &dummy;
int carry = 0;
while (l1 || l2 || carry) {
int sum = carry;
if (l1) { sum += l1->val; l1 = l1->next; }
if (l2) { sum += l2->val; l2 = l2->next; }
tail->next = new ListNode(sum % 10);
tail = tail->next;
carry = sum / 10;
}
return dummy.next;
}
};
// Java
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), tail = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = carry;
if (l1 != null) { sum += l1.val; l1 = l1.next; }
if (l2 != null) { sum += l2.val; l2 = l2.next; }
tail.next = new ListNode(sum % 10);
tail = tail.next;
carry = sum / 10;
}
return dummy.next;
}
}
#include
using namespace std;
struct ListNode {
int val; ListNode *next;
ListNode(int x): val(x), next(nullptr) {}
};
ListNode* createList(int n) {
ListNode *head = nullptr, *tail = nullptr;
for (int i = 0, x; i < n && cin >> x; i++) {
ListNode *node = new ListNode(x);
if (!head) head = tail = node;
else { tail->next = node; tail = node; }
}
return head;
}
void printList(ListNode* head) {
while (head) { cout << head->val << " "; head = head->next; }
cout << endl;
}
int main() {
int n = 3;
ListNode* l1 = createList(n);
ListNode* l2 = createList(n);
Solution sol;
ListNode* res = sol.addTwoNumbers(l1, l2);
printList(res);
return 0;
}