Description:
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 Explanation: 342 + 465 = 807.
solution:
A few things to consider:
- carry
- Linked lists have different lengths
- A better way to do it
The first time I wrote the code, it was very long, and I had to debug it several times, and it was O(n) time.
/** * 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 carry = 0; ListNode * tmp = new ListNode(-1); ListNode * l3 = tmp; ListNode * res = l3; int num = 0; int val = 0; while (l1 ! = NULL && l2 ! = NULL) { num = l1->val + l2->val + carry; if (num >= 10){ carry = 1 ; val = num -carry * 10 ; } else { carry = 0; val = num; } tmp = new ListNode(val); l3->next = tmp; l1 = l1->next; l2 = l2->next; l3 = l3->next; } if (l1 == NULL || l2 == NULL) { ListNode * tmp1 = NULL; if (l1 ! = NULL) { tmp1 = l1; } else { tmp1 = l2; } while (tmp1 ! = NULL) { num = tmp1->val + carry; if (num >= 10){ carry = 1; val = num -carry * 10 ; } else { carry = 0; val = num; } tmp = new ListNode(val); l3->next = tmp; l3 = l3->next; tmp1 = tmp1->next; } } if (carry == 1){ tmp = new ListNode(1); l3->next = tmp; } return res->next; }};Copy the code
Your own simplified version (write this question later, you need to come up with a concise enough version immediately) :