You are given two non-empty linked lists rePResenting two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
链表顺序与数字顺序相反,表头存放的是数字的最低位,(2 -> 4 -> 3) + (5 -> 6 -> 4)即342+465=807,可以直接在链表上进行对应位的加法,向后进位。 因为题目中说了是非空链表,所以初始不再考虑l1和l2为空的情况; l1和l2长度可能不同,对于较长链表剩余的高位,与0相加得到结果;
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int sum = l1->val + l2->val; ListNode* l3 = new ListNode(sum%10); ListNode* node = l3; l1 = l1->next; l2 = l2->next; sum = sum/10; while( l1!=NULL || l2!=NULL || sum != 0) { int n1 = 0, n2 = 0; if (l1!=NULL) { n1 = l1->val; l1 = l1->next; } if (l2!=NULL) { n2 = l2->val; l2 = l2->next; } sum+= n1 + n2; node->next = new ListNode(sum%10); node = node->next; sum = sum/10; } return l3; }};新闻热点
疑难解答