python链表多项式加多项式
时间: 2023-10-05 19:12:55 浏览: 90
以下是Python实现的链表多项式加多项式的示例代码:
```python
class Node:
def __init__(self, coeff, exp, next=None):
self.coeff = coeff
self.exp = exp
self.next = next
class Polynomial:
def __init__(self, head=None):
self.head = head
def insert(self, coeff, exp):
if self.head is None:
self.head = Node(coeff, exp)
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = Node(coeff, exp)
def add(self, poly2):
result = Polynomial()
curr1 = self.head
curr2 = poly2.head
while curr1 is not None and curr2 is not None:
if curr1.exp > curr2.exp:
result.insert(curr1.coeff, curr1.exp)
curr1 = curr1.next
elif curr1.exp < curr2.exp:
result.insert(curr2.coeff, curr2.exp)
curr2 = curr2.next
else:
result.insert(curr1.coeff + curr2.coeff, curr1.exp)
curr1 = curr1.next
curr2 = curr2.next
while curr1 is not None:
result.insert(curr1.coeff, curr1.exp)
curr1 = curr1.next
while curr2 is not None:
result.insert(curr2.coeff, curr2.exp)
curr2 = curr2.next
return result
def display(self):
curr = self.head
while curr is not None:
print(curr.coeff, "x^", curr.exp, end=" ")
curr = curr.next
print()
# 示例
p1 = Polynomial()
p1.insert(1, 2)
p1.insert(2, 1)
p1.insert(3, 0)
p2 = Polynomial()
p2.insert(2, 1)
p2.insert(1, 0)
p3 = p1.add(p2)
p1.display() # 输出 "1 x^ 2 2 x^ 1 3 x^ 0"
p2.display() # 输出 "2 x^ 1 1 x^ 0"
p3.display() # 输出 "1 x^ 2 4 x^ 1 4 x^ 0"
```
以上代码中,`Node`类表示链表节点,包含系数和指数两个属性,以及指向下一个节点的指针。`Polynomial`类表示多项式,包含一个链表作为成员变量,支持插入节点、多项式加法和显示多项式等操作。在多项式加法中,使用两个指针分别指向两个多项式的头节点,遍历链表将相同指数的项相加,并将结果插入到结果多项式中。最后,将剩余的项依次插入到结果多项式中。
阅读全文