python 链表 多项式
时间: 2023-11-17 15:07:59 浏览: 69
多项式可以使用链表来实现,每个节点存储多项式的系数和指数。以下是Python链表实现多项式的示例代码:
```python
class Node:
def __init__(self, coef, exp):
self.coef = coef
self.exp = exp
self.next = None
class Polynomial:
def __init__(self):
self.head = None
def insert(self, coef, exp):
node = Node(coef, exp)
if self.head is None:
self.head = node
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = node
def add(self, poly):
result = Polynomial()
curr1 = self.head
curr2 = poly.head
while curr1 is not None and curr2 is not None:
if curr1.exp == curr2.exp:
result.insert(curr1.coef + curr2.coef, curr1.exp)
curr1 = curr1.next
curr2 = curr2.next
elif curr1.exp > curr2.exp:
result.insert(curr1.coef, curr1.exp)
curr1 = curr1.next
else:
result.insert(curr2.coef, curr2.exp)
curr2 = curr2.next
while curr1 is not None:
result.insert(curr1.coef, curr1.exp)
curr1 = curr1.next
while curr2 is not None:
result.insert(curr2.coef, curr2.exp)
curr2 = curr2.next
return result
def display(self):
curr = self.head
while curr is not None:
print(curr.coef, 'x^', curr.exp, end=' ')
curr = curr.next
print()
# 示例代码
p1 = Polynomial()
p1.insert(1, 1)
p1.insert(3, 2)
p1.insert(-5, 5)
p1.insert(7, 0)
p1.display()
p2 = Polynomial()
p2.insert(0, 0)
p2.insert(2, 2)
p2.insert(6, 3)
p2.insert(1, 5)
p2.insert(-4, 6)
p2.display()
result = p1.add(p2)
result.display()
```
阅读全文