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
主要是考虑进位
Subscribe to see which companies asked this question
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /* * 1.设置进位为0,并判断列表是否为空 * 2.两个列表都不为空时,遍历,判断两个列表对应的值相加后是否大于10,大于就设置进位为1,否则为0 * 3.一个列表为空的时候,进位+列表的对应的值,然后将剩下的添加到结果列表的尾部.
* 4.两个列表都为空,进位位1,也添加 */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (NULL == l1 && NULL == l2) { return NULL; } else if (NULL == l1) { return l2; } else if (NULL == l2) { return l1; } ListNode* p1 = l1; ListNode* p2 = l2; ListNode* res_head = NULL; ListNode* res_index = NULL; int flag = 0; while (p1 != NULL && p2 != NULL) { int sum = p1->val + p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); if (NULL == res_head) { res_head = res_node; res_index = res_head; } else { res_index->next = res_node; res_index = res_node; } p1 = p1->next; p2 = p2->next; } while (p1 != NULL) { int sum = p1->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p1 = p1->next; } while (p2 != NULL) { int sum = p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p2 = p2->next; } if (0 != flag) { ListNode* res_node = new ListNode(flag); res_index->next = res_node; res_index = res_node; } return res_head; } };