链表实现大整数相加

 

#include <bits/stdc++.h>
using namespace std;

typedef struct node
{
    int value;
    node *next;
}linklist;

linklist* ReverseList(linklist *head){
    linklist *next;
    linklist *pre = NULL;
    while (head != NULL) {
        next = head->next;
        head->next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

linklist* ADD(linklist*L1, linklist*L2){
    linklist *l1 = ReverseList(L1);
    linklist *l2 = ReverseList(L2);
    linklist *res = NULL, *p;
    int num = 0, sum;
    while(l1 || l2){
        if(l1 && l2){
            sum = l1->value + l2->value + num;
            l1 = l1->next;
            l2 = l2->next;
        } else if(l1){
            sum = l1->value + num;
            l1 = l1->next;
        } else if(l2){
            sum = l2->value + num;
            l2 = l2->next;
        }

        num = sum/10;
        sum = sum%10;
        linklist *tmp = new linklist();
        tmp->value = sum;

        if(res == NULL){
            res = tmp;
            p = res;
        } 
        else {
            p->next = tmp;
            p = p->next;
        }
    }
    res = ReverseList(res);
    return res;
}

linklist* CreateList(int Size){
    int num;
    linklist *head = NULL, *p;
    while(Size--){
        cin >> num;
        linklist *tmp = new linklist();
        tmp->value = num;
        if(head == NULL){
            head = tmp;
            p = head;
        }else {
            p->next = tmp;
            p = p->next;
        }
    }
    return head;
}

void PRINT(linklist *head){
    linklist *p = head;
    if(p != NULL){
        cout << p->value;
        p = p->next;
    }
    while(p != NULL){
        cout << "->" << p->value ;
        p=p->next;
    }
    cout << endl;
}


int main(){

    int n, m;
    cin >> n >> m;
    linklist *L1 = CreateList(n);
    //PRINT(L1);
    linklist *L2 = CreateList(m);
    //PRINT(L2);
    linklist *L3 = ADD(L1, L2);
    PRINT(L3);
    return 0;
}
/*
输入:
5 3
3 1 4 6 7
2 3 3
输出结果:
3->1->7->0->0

时间复杂度为O(max(n,m)),空间复杂度为O(max(n,m));
若可以修改原链表结构,可将空间复杂度降为O(1);
*/

 

posted @ 2020-09-15 18:03  西瓜不懂柠檬的酸  Views(472)  Comments(0Edit  收藏  举报
levels of contents