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[Solution]
本题比较简单,只是简单的链表操作,只是不要忘记最后进位情况。
1 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 2 { 3 ListNode dummy, *p = NULL; 4 int carry = 0; 5 6 p = &dummy; 7 while (l1 != NULL | l2 != NULL) 8 { 9 int sum = (l1 == NULL) ? 0 : l1->val + (l2 == NULL) ? 0 : l2->val + carry;10 p->next = new ListNode(sum % 10);11 p = p->next;12 carry = sum / 10;13 if (l1)14 l1 = l1->next;15 if (l2)16 l2 = l2->next;17 }18 if (carry)19 p->next = new ListNode(carry);20 21 return dummy.next;22 }