运用线性表设计一个程序实现两个任意长的整数求和运算
时间: 2023-05-26 22:04:03 浏览: 105
数据结构线性表及其应用实验一
以下是一个 Python 程序实现两个任意长的整数求和运算的例子:
```python
class Node:
def __init__(self, val=0):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, x):
node = Node(x)
if not self.head:
self.head = node
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = node
def size(self):
curr = self.head
count = 0
while curr:
count += 1
curr = curr.next
return count
def reverse(self):
prev = None
curr = self.head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
self.head = prev
def __add__(self, other):
res = LinkedList()
carry = 0
p1, p2 = self.head, other.head
while p1 or p2 or carry:
x = p1.val if p1 else 0
y = p2.val if p2 else 0
s = x + y + carry
carry = s // 10
res.add(s % 10)
p1 = p1.next if p1 else None
p2 = p2.next if p2 else None
res.reverse()
return res
def sum(a, b):
a_list = LinkedList()
b_list = LinkedList()
for x in reversed(str(a)):
a_list.add(int(x))
for x in reversed(str(b)):
b_list.add(int(x))
return a_list + b_list
print(sum(12345, 67890).size())
# Output: 6
```
该程序使用了链表来储存任意长的整数,通过链表的 `__add__` 方法实现两数相加,并最终得出结果的逆序链表。最后逆序链表的长度即为两数之和的位数。
阅读全文