本文实例为大家分享了C++单链表实现大数加法,供大家参考,具体内容如下
Input Format
输入文件包括两行。
- 第一行包括一个正整数,保证位数不超过1000000。
- 第二行包括一个正整数,保证位数不超过1000000。
Output Format
输出文件包括一行。
- 第一行包括一个正整数。
Sample Input
10558
22
Sample Output
10580
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
#include <iostream> using namespace std; class BigData { friend ostream &operator<<(ostream &os, const BigData &x); friend istream &operator>>(istream &is, BigData &x); friend BigData operator+(BigData a, BigData b); private : struct node { int data; node *next; node( const short &x, node *n = NULL) { data = x; next = n; } }; node *num; void clear(); public : BigData(node *p = NULL) { if (p == NULL) { num = new node(0); } else { num = p; }; } BigData( const BigData &); ~BigData() { clear(); } BigData &operator=( const BigData &); }; BigData::BigData( const BigData &x) { num = new node(x.num->data); node *p = num, *q = x.num; while (q->next != NULL) { q = q->next; p->next = new node(q->data); p = p->next; } } void BigData::clear() { node *p = num, *q; while (p != NULL) { q = p; p = p->next; delete q; } num = NULL; } BigData operator+(BigData a, BigData b) { BigData tmp; BigData::node *p, *q, *end; int carry; tmp.num = end = new BigData::node(a.num->data + b.num->data); carry = tmp.num->data / 10; tmp.num->data %= 10; p = a.num->next; q = b.num->next; end = tmp.num; while (p != NULL && q != NULL) { end->next = new BigData::node(p->data + q->data + carry); end = end->next; carry = end->data / 10; end->data %= 10; p = p->next; q = q->next; } if (p == NULL)p = q; while (p != NULL) { end->next = new BigData::node(p->data + carry); end = end->next; carry = end->data / 10; end->data %= 10; p = p->next; } if (carry != 0) { end->next = new BigData::node(carry); return tmp; } } BigData &BigData::operator=( const BigData &x) { if (&x == this ) return * this ; clear(); num = new node(x.num->data); node *p = num, *q = x.num; while (q->next != NULL) { q = q->next; p->next = new node(q->data); p = p->next; } return * this ; } istream &operator>>(istream &is, BigData &x) { char ch; x.clear(); while ((ch = is.get()) != '\n' ) { x.num = new BigData::node(ch - '0' , x.num); } return is; } ostream &operator<<(ostream &os, const BigData &x) { string s; BigData::node *p = x.num; while (p != NULL) { s = char (p->data + '0' ) + s; p = p->next; } for ( int i = 0; i < s.size(); ++i)os << s[i]; return os; } int main() { BigData a, b, c; cin >> a >> b; c = a + b; cout << c; } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_43338264/article/details/102216217