LeetCode 2

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:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* t1 = l1, *t2 = l2, *t;
    while(t1 != NULL && t2 != NULL){
        t1->val += t2->val;
        if(t1->val / 10 == 1) {
            t1->val %= 10;
            if (t1->next != NULL) {
                t1->next->val++;
            } else {
                if (t2->next != NULL) {
                    t2->next->val++;
                } else {
                    ListNode *Temp = new ListNode(1);
                    t1->next = Temp;
                }
            }
        }
        t2->val = t1->val;
        t1 = t1->next;
        t2 = t2->next;
    }
    if(t1 != NULL){
        t = l1;
    }else{
        t = l2;
        t1 = t2;
    }
    while(t1 != NULL && t1->val / 10 == 1){
        t1->val %= 10;
        if(t1->next == NULL) {
            ListNode *Temp = new ListNode(1);
            t1->next = Temp;
            break;
        }else{
            t1->next->val++;
            t1 = t1->next;
        }
    }
    return t;
}

PS.

这个题卡在了构造新节点上。

开始时候用了:

ListNode Temp = ListNode(1);
t1->next = &Temp;

报错如下:

Input:
[5]
[5]
Answer:
double free or corruption (out): 0x00007ffc146b4e40 ***

后来改用:

ListNode *Temp = new ListNode(1);
t1->next = Temp;

Accepted

猜你喜欢

转载自www.cnblogs.com/QinHaotong/p/9573709.html
今日推荐