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:
需要思考到几点:
- 进位
- 链表的长度不相同
- 更好的实现方法
第一遍写代码的时候,写的很长,而且调试了好几次才过的,时间复杂度O(n)。
/**
* 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;
}
};
自己简化后的版本(以后再写这个题,需要马上想到足够精简的版本):