# 链表实现大数加法

## 代码

//main.cpp

using std::cout;
using std::endl;
using std::cin;
int main() {
string s1, s2;
// 0 < s1.length(),s2.length() <= 10000
cout << "Input two Numbers" << endl;
cin >> s1 >> s2;
List l1(s1), l2(s2);
List l3 = l1 + l2;
cout << "After " << l1 << " + " << l2 <<endl;
cout << l3 << endl << "Size : " << l3.size() << endl;
List l4;
l4 = l3 + l1;
cout << "After " << l3 << " + " << l1 << endl;
cout << l4 << endl << "Size : " << l4.size() << endl;
}
//ListAdd.hpp

#include <iostream>
using std::string;
using std::ostream;
class List {
private:
struct node {
int val;
node* next;
node(int v, node* n = 0):val(v), next(n){}
};
int _size;
public:
List();
List(const List& other);
List(const string & num);
void clear();
void push_front(int val);   // 在头部插入数值
List operator+(const List& other);    //在这里进行链表加法实现
List& operator=(const List& other);   // 赋值操作重载
int size() const;
~List();
friend ostream& operator<<(ostream & os, const List &  out);
// 输出数字，无需换行
};
#endif
//ListAdd.cpp

List::List() {
_size = 0;
}

List::List(const List& other) {
int* num = new int[other._size];
int i = other._size - 1;
while (current != 0) {
num[i] = current->val;
i--;
current = current->next;
}
_size = 0;
for (int i = 0; i < other._size; i++)
push_front(num[i]);
delete []num;
}

List::List(const string& num) {
_size = 0;
for (int i = 0; i < num.size(); i++)
push_front(num[i] - 48);
}

void List::clear() {
delete temp;
}
_size = 0;
}

void List::push_front(int val) {
node* temp = new node(val, head);
_size++;
}

List List::operator+(const List& other) {
int max = _size > other._size ? _size : other._size;
char* addNum = new char[max + 1];
int carry = 0;
List result;
if (_size > other._size) {
int i = 0;
while (c2 != 0) {
addNum[i++] = (c1->val + c2->val + carry) % 10 + 48;
carry = (c1->val + c2->val + carry) / 10;
c1 = c1->next;
c2 = c2->next;
}
while (c1 != 0) {
addNum[i++] = (c1->val + carry) % 10 + 48;
carry = (c1->val + carry) / 10;
c1 = c1->next;
}
} else {
int i = 0;
while (c2 != 0) {
addNum[i++] = (c1->val + c2->val + carry) % 10 + 48;
carry = (c1->val + c2->val + carry) / 10;
c1 = c1->next;
c2 = c2->next;
}
while (c1 != 0) {
addNum[i++] = (c1->val + carry) % 10 + 48;
carry = (c1->val + carry) / 10;
c1 = c1->next;
}
}
for (int i = max; i >= 0; i--)
} else {
for (int i = max - 1; i >= 0; i--)
}
return result;
}

List& List::operator=(const List& other) {
int* num = new int[other._size];
int i = other._size - 1;
while (current != 0) {
num[i] = current->val;
i--;
current = current->next;
}
_size = 0;
for (int i = 0; i < other._size; i++)
push_front(num[i]);
while (temp != 0) {
node* t = temp;
temp = temp->next;
delete t;
}
delete []num;
return *this;
}

int List::size() const  { return _size; }

List::~List() {
clear();
}

ostream& operator<<(ostream& os, const List& out) {
char* num = new char[out._size + 1];
}