一元多项式的运算数据结构
时间: 2023-10-17 13:27:09 浏览: 131
数据结构一元多项式的运算.pdf
一元多项式可以使用链表来实现运算的数据结构。每个节点表示多项式中的一个项,包含一个系数和一个指数。链表的每个节点按照指数降序排列,方便进行运算。
具体的数据结构可以设计如下:
```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 insert_term(self, coefficient, exponent):
# 按照指数降序插入节点
new_node = Node(coefficient, exponent)
if self.head is None or exponent > self.head.exponent:
new_node.next = self.head
self.head = new_node
else:
current = self.head
while current.next and current.next.exponent >= exponent:
current = current.next
new_node.next = current.next
current.next = new_node
def add(self, polynomial):
# 多项式相加
result = Polynomial()
current1 = self.head
current2 = polynomial.head
while current1 and current2:
if current1.exponent > current2.exponent:
result.insert_term(current1.coefficient, current1.exponent)
current1 = current1.next
elif current1.exponent < current2.exponent:
result.insert_term(current2.coefficient, current2.exponent)
current2 = current2.next
else:
result.insert_term(current1.coefficient + current2.coefficient, current1.exponent)
current1 = current1.next
current2 = current2.next
# 处理剩余的节点
while current1:
result.insert_term(current1.coefficient, current1.exponent)
current1 = current1.next
while current2:
result.insert_term(current2.coefficient, current2.exponent)
current2 = current2.next
return result
def multiply(self, polynomial):
# 多项式相乘
result = Polynomial()
current1 = self.head
while current1:
current2 = polynomial.head
while current2:
result.insert_term(current1.coefficient * current2.coefficient, current1.exponent + current2.exponent)
current2 = current2.next
current1 = current1.next
return result
def display(self):
# 打印多项式
if self.head is None:
print("Empty polynomial")
else:
current = self.head
while current:
if current.coefficient == 0:
current = current.next
continue
if current.coefficient > 0:
print("+", end="")
print(current.coefficient, end="")
if current.exponent > 0:
print("x^" + str(current.exponent), end="")
current = current.next
print()
```
使用上述数据结构,可以创建两个多项式对象,进行加法和乘法运算,并输出结果。
阅读全文