多项式相加(链表版)文件
时间: 2023-07-11 08:51:42 浏览: 83
抱歉,我是一个语言模型AI,无法为您提供文件。但是,我可以为您提供多项式相加(链表版)的代码示例:
```python
class Node:
def __init__(self, coef, exp, next=None):
self.coef = coef
self.exp = exp
self.next = next
class Polynomial:
def __init__(self):
self.head = None
def insert(self, coef, exp):
if self.head is None:
self.head = Node(coef, exp)
else:
current = self.head
previous = None
while current is not None and current.exp > exp:
previous = current
current = current.next
if current is not None and current.exp == exp:
current.coef += coef
else:
newNode = Node(coef, exp)
newNode.next = current
if previous is not None:
previous.next = newNode
else:
self.head = newNode
def add(self, poly):
result = Polynomial()
current1 = self.head
current2 = poly.head
while current1 is not None and current2 is not None:
if current1.exp == current2.exp:
result.insert(current1.coef + current2.coef, current1.exp)
current1 = current1.next
current2 = current2.next
elif current1.exp > current2.exp:
result.insert(current1.coef, current1.exp)
current1 = current1.next
else:
result.insert(current2.coef, current2.exp)
current2 = current2.next
while current1 is not None:
result.insert(current1.coef, current1.exp)
current1 = current1.next
while current2 is not None:
result.insert(current2.coef, current2.exp)
current2 = current2.next
return result
def display(self):
current = self.head
while current is not None:
print(current.coef, "x^", current.exp, end=" + ")
current = current.next
poly1 = Polynomial()
poly1.insert(5, 2)
poly1.insert(3, 1)
poly1.insert(2, 0)
print("First polynomial:")
poly1.display()
poly2 = Polynomial()
poly2.insert(7, 1)
poly2.insert(4, 0)
print("Second polynomial:")
poly2.display()
result = poly1.add(poly2)
print("Resultant polynomial:")
result.display()
```
这是一个Python的链表实现,它使用两个Node类,一个是用来表示多项式的节点,另一个是用来表示多项式的类。在多项式类中,有三个方法:insert(用于插入多项式节点)、add(用于将两个多项式相加)、display(用于显示多项式)。
测试代码创建两个多项式,将它们相加并显示结果。
阅读全文