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
大非负整数相加,注意数字是怎么表示的就好,链表头是低位,尾是高位,另外最后一位记得处理,也不要忘了0的情况。
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* p1 = l1, *p2 = l2; 13 ListNode* ret = NULL; 14 ListNode* p = ret; 15 // 逐位相加 16 while (p1 != NULL && p2 != NULL) { 17 ListNode* tmp = new ListNode(p1->val + p2->val); 18 // 判断是不是链表头 19 if (ret == NULL) { 20 ret = tmp; 21 p = ret; 22 } else { 23 p->next = tmp; 24 p = tmp; 25 } 26 p1 = p1->next; 27 p2 = p2->next; 28 } 29 30 if (p1 != NULL) { 31 p->next = p1; 32 } 33 if (p2 != NULL) { 34 p->next = p2; 35 } 36 37 // 为空时要返回0 38 if (ret == NULL) 39 return new ListNode(0); 40 41 // 处理进位问题 42 p = ret; 43 while (p->next != NULL) { 44 p->next->val += p->val / 10; 45 p->val = p->val % 10; 46 p = p->next; 47 } 48 // 处理最高位 49 if (p->val >= 10) { 50 ListNode* tmp = new ListNode(p->val / 10); 51 p->next = tmp; 52 p->val = p->val % 10; 53 } 54 55 return ret; 56 57 } 58 };