用链表编写算法实现一元多项式相加及所写代码
时间: 2024-05-05 10:18:21 浏览: 87
可以参考以下代码实现:
```python
class Node:
def __init__(self, coefficient, exponent):
self.coefficient = coefficient
self.exponent = exponent
self.next = None
class Polynomial:
def __init__(self):
self.head = None
def add_node(self, coefficient, exponent):
new_node = Node(coefficient, exponent)
if not self.head:
self.head = new_node
return
curr = self.head
prev = None
while curr and curr.exponent > exponent:
prev = curr
curr = curr.next
if curr and curr.exponent == exponent:
curr.coefficient += coefficient
if curr.coefficient == 0:
self.remove_node(curr, prev)
else:
new_node.next = curr
if prev:
prev.next = new_node
else:
self.head = new_node
def remove_node(self, curr, prev):
if prev:
prev.next = curr.next
else:
self.head = curr.next
def __str__(self):
if not self.head:
return "0"
res = []
curr = self.head
while curr:
if curr.coefficient != 0:
res.append("{}x^{}".format(curr.coefficient, curr.exponent))
curr = curr.next
return " + ".join(res)
def __add__(self, other):
res = Polynomial()
curr = self.head
while curr:
res.add_node(curr.coefficient, curr.exponent)
curr = curr.next
curr = other.head
while curr:
res.add_node(curr.coefficient, curr.exponent)
curr = curr.next
return res
```
实现了一个 `Node` 类和 `Polynomial` 类,其中 `Node` 存储了一项多项式的系数和指数,`Polynomial` 存储了多项式的链表,支持添加节点、移除节点、多项式的字符串表示和相加操作。
阅读全文