leetcode-2-两数相加(链表)

#include<vector>
#include<map>
#include<iostream>
#include<memory>
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
    
};

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    if (l1 == NULL)
        return l2;
    if (l2 == NULL)
        return l1;
    ListNode head(0);
    ListNode* pre = &head;
    int twosum;
    bool carryflag = false;//进位标记位
    while (l1 != NULL && l2 != NULL)
    {
        twosum = l1->val + l2->val + carryflag;
        carryflag = twosum / 10;
        ListNode* p = new ListNode(twosum % 10);
        pre->next = p;
        pre = p;
        l1 = l1->next;
        l2 = l2->next;
    }
    if (l1 != NULL) {
        while (l1 != NULL) {
            ListNode* p;
            if (carryflag) {
                twosum = l1->val + carryflag;
                carryflag = twosum / 10;
                p = new ListNode(twosum%10);
            }
            else
                p = new ListNode(l1->val);
            pre->next = p;
            pre = p;
            l1 = l1->next;
        }
    }
    else if (l2 != NULL) {
        while (l2 != NULL) {
            ListNode* p;
            if (carryflag) {
                twosum = l2->val + carryflag;
                carryflag = twosum / 10;
                p = new ListNode(twosum%10);
            }
            else
                p = new ListNode(l2->val);
            pre->next = p;
            pre = p;
            l2 = l2->next;
        }
    }
    if (carryflag) {
        ListNode* p = new ListNode(carryflag);
        pre->next = p;
        pre = p;
    }
    pre->next = NULL;
    return head.next;
}

void ListTravel(ListNode*p)
{
    cout << "ADDR(" << p << ")  ";
    while (p != NULL)
    {
        cout << p->val << "\t";
        p = p->next;
    }cout << endl;
}

int main()
{
    ListNode p1(2), p2(4), p3(3);
    ListNode q1(5), q2(6), q3(4);
    p1.next = &p2; p2.next = &p3; p3.next = NULL;
    q1.next = &q2; q2.next = &q3; q3.next = NULL;
    ListTravel(&p1);
    ListTravel(&q1);
    auto i = addTwoNumbers(&p1, &q1);
    ListTravel(i);
}
posted @ 2020-09-16 13:10  shadowgully  阅读(96)  评论(0编辑  收藏  举报