2. Add Two Numbers
My SubmissionsTotal Accepted: 123735 Total Submissions: 554195 Difficulty: Medium
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
Show Similar Problems
new 新的节点参考了:
核心代码:
1 ListNode *p = new ListNode(sum % 10); 2
比较好的思路:
直接用了 取余 和 /10 操作,少一步判断 是否要进位。
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* tail = NULL; 13 ListNode* head = NULL; 14 int sum = 0; 15 while(l1 != NULL || l2 != NULL){ 16 if(l1 != NULL){ 17 sum += l1->val; 18 l1 = l1->next; 19 } 20 if(l2 != NULL){ 21 sum += l2->val; 22 l2 = l2->next; 23 } 24 ListNode *p = new ListNode(sum % 10); 25 if (head == NULL) { 26 head = p; 27 tail = p; 28 } else { 29 tail->next = p; 30 tail = p; 31 } 32 sum /= 10; 33 } 34 if(sum != 0){ 35 ListNode *p = new ListNode(sum % 10); 36 tail->next = p; 37 tail = p; 38 } 39 tail->next = NULL; 40 return head; 41 } 42 };