用双向链表实现超长整数加减法
时间: 2023-07-11 16:51:13 浏览: 55
好的,我可以为您解答这个问题。
首先,我们需要定义一个双向链表结构体,包含三个成员变量:前驱节点指针、后继节点指针和当前节点的值。代码如下:
```c++
struct Node {
Node *prev, *next;
int val;
};
```
接下来,我们可以定义一个类来实现超长整数的加减法。在这个类中,我们需要定义两个双向链表,分别存储两个超长整数的每一位。加法操作需要从链表的尾部开始遍历,同时在遍历的过程中需要考虑进位。减法操作需要先比较两个超长整数的大小,然后从链表的尾部开始遍历,同时在遍历的过程中需要考虑借位。
下面是一个示例代码,可以实现超长整数的加减法:
```c++
class LongInt {
public:
LongInt() {
head1 = new Node;
head2 = new Node;
tail1 = head1;
tail2 = head2;
head1->prev = NULL;
head2->prev = NULL;
head1->next = tail1;
head2->next = tail2;
tail1->prev = head1;
tail2->prev = head2;
tail1->next = NULL;
tail2->next = NULL;
}
void add(int x) {
Node *node = new Node;
node->val = x;
node->prev = tail1;
node->next = tail1->next;
tail1->next = node;
tail1 = node;
}
void sub(int x) {
Node *node = new Node;
node->val = x;
node->prev = tail2;
node->next = tail2->next;
tail2->next = node;
tail2 = node;
}
LongInt operator+(const LongInt& other) const {
LongInt res;
Node *p = tail1->prev;
Node *q = other.tail1->prev;
int carry = 0;
while (p != head1->prev || q != other.head1->prev || carry != 0) {
int x = (p != head1->prev ? p->val : 0);
int y = (q != other.head1->prev ? q->val : 0);
int sum = x + y + carry;
carry = sum / 10;
sum %= 10;
res.add(sum);
if (p != head1->prev) p = p->prev;
if (q != other.head1->prev) q = q->prev;
}
return res;
}
LongInt operator-(const LongInt& other) const {
LongInt res;
Node *p = tail1->prev;
Node *q = other.tail1->prev;
bool borrow = false;
if (compare(other) < 0) {
borrow = true;
std::swap(p, q);
}
while (p != head1->prev || q != other.head1->prev) {
int x = (p != head1->prev ? p->val : 0);
int y = (q != other.head1->prev ? q->val : 0);
if (borrow) x--;
if (x < y) {
x += 10;
borrow = true;
} else {
borrow = false;
}
int diff = x - y;
res.sub(diff);
if (p != head1->prev) p = p->prev;
if (q != other.head1->prev) q = q->prev;
}
return res;
}
int compare(const LongInt& other) const {
Node *p = tail1->prev;
Node *q = other.tail1->prev;
while (p != head1->prev || q != other.head1->prev) {
int x = (p != head1->prev ? p->val : 0);
int y = (q != other.head1->prev ? q->val : 0);
if (x > y) {
return 1;
} else if (x < y) {
return -1;
}
if (p != head1->prev) p = p->prev;
if (q != other.head1->prev) q = q->prev;
}
return 0;
}
private:
Node *head1, *head2, *tail1, *tail2;
};
```
使用示例:
```c++
LongInt a, b;
a.add(9);
a.add(9);
a.add(9);
b.add(1);
b.add(0);
LongInt c = a + b;
LongInt d = a - b;
```
在这个示例中,我们创建了两个超长整数 a 和 b,然后分别添加了三个数字和两个数字。接着,我们通过重载运算符实现了加法和减法操作,并将结果存储在变量 c 和 d 中。