【链表】2. 两数相加
题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解法:
(1)将两个链表看成是相同长度的进行遍历,如果一个链表较短则前面补0,比如987+23=987+023=1010;
(2)每一位计算的同时需要考虑上一位的进位问题,而当前位计算结束后同样需要更新进位值;
(3)如果两个链表全部遍历完毕,进位值为1,则在新链表最前方添加节点1;
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 *pre = new ListNode(0); 13 ListNode *cur = pre; 14 15 int carry = 0; 16 17 while (l1 != NULL || l2 != NULL) 18 { 19 int x = l1 == NULL ? 0 : l1->val; 20 int y = l2 == NULL ? 0 : l2->val; 21 int sum = x + y + carry; 22 23 carry = sum / 10; 24 sum = sum % 10; 25 cur->next = new ListNode(sum); 26 27 cur = cur->next; 28 29 if (l1 != NULL) 30 { 31 l1 = l1->next; 32 } 33 if (l2 != NULL) 34 { 35 l2 = l2->next; 36 } 37 } 38 39 if (carry == 1) 40 { 41 cur->next = new ListNode(carry); 42 } 43 44 return pre->next; 45 } 46 };