python链表实现多项式乘多项式
时间: 2023-10-09 18:16:37 浏览: 115
用链表实现多项式的加法和乘法
以下是Python链表实现多项式乘多项式的代码:
```python
class Node:
def __init__(self, coefficient, exponent, next=None):
self.coefficient = coefficient
self.exponent = exponent
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add_term(self, coefficient, exponent):
if self.head is None:
self.head = Node(coefficient, exponent)
else:
current = self.head
while current.next is not None:
current = current.next
current.next = Node(coefficient, exponent)
def print_list(self):
current = self.head
while current is not None:
print(f"{current.coefficient}x^{current.exponent}", end="")
if current.next is not None:
print(" + ", end="")
current = current.next
print()
def multiply(self, other):
result = LinkedList()
current = self.head
while current is not None:
current_other = other.head
while current_other is not None:
coefficient = current.coefficient * current_other.coefficient
exponent = current.exponent + current_other.exponent
result.add_term(coefficient, exponent)
current_other = current_other.next
current = current.next
return result
poly1 = LinkedList()
poly1.add_term(2, 3)
poly1.add_term(5, 2)
poly1.add_term(1, 0)
print("Polynomial 1: ", end="")
poly1.print_list())
poly2 = LinkedList()
poly2.add_term(3, 2)
poly2.add_term(2, 1)
poly2.add_term(1, 0)
print("Polynomial 2: ", end="")
poly2.print_list()
result = poly1.multiply(poly2)
print("Result: ", end="")
result.print_list()
```
在这个实现中,我们定义了一个`Node`类来表示多项式中的每个项。每个节点包含一个系数和指数,并且可以链接到下一个节点。我们还定义了一个`LinkedList`类来表示整个多项式。这个类包含一个头节点,并且可以添加一个新的项。我们还定义了一个`multiply`函数,用于将一个多项式乘以另一个多项式,并返回一个新的多项式作为结果。
在这个代码中,我们首先创建了两个多项式,然后将它们打印出来。接下来,我们将这两个多项式相乘,并将结果打印出来。
阅读全文