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
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 ListNode *head = new ListNode(0); 13 ListNode *p = head, *p1 = l1, *p2 = l2; 14 int val, val1, val2; 15 int carry = 0; 16 while (p1 != NULL || p2 != NULL) { 17 val1 = val2 = 0; 18 if (p1 != NULL) { 19 val1 = p1->val; 20 p1 = p1->next; 21 } 22 if (p2 != NULL) { 23 val2 = p2->val; 24 p2 = p2->next; 25 } 26 val = val1 + val2 + carry; 27 carry = val / 10; 28 val %= 10; 29 p->next = new ListNode(val); 30 p = p->next; 31 } 32 if (carry != 0) { 33 p->next = new ListNode(carry); 34 } 35 ListNode *sum = head->next; 36 delete head; 37 return sum; 38 } 39 };
时间: 2024-10-13 00:12:01