定义单链表的节点类和单链表类(参考附件),对如下的 PA(x)和PB(x)两个多项式求和,求和代码参考如下附图 。 PA(x)=3x11+7x8+4x3+5 , PB(x)=8x117x8+10x6
时间: 2024-01-05 12:02:18 浏览: 22
好的,根据您的要求,我为您提供一个Python实现的单链表节点类和单链表类,并实现PA(x)和PB(x)两个多项式的求和。代码如下:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = ListNode()
def add(self, val):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = ListNode(val)
def __str__(self):
cur = self.head.next
s = ''
while cur is not None:
s += str(cur.val) + ' -> '
cur = cur.next
return s + 'None'
def add_poly(poly1, poly2):
res = LinkedList()
cur1, cur2 = poly1.head.next, poly2.head.next
while cur1 and cur2:
if cur1.val[1] == cur2.val[1]:
res.add((cur1.val[0] + cur2.val[0], cur1.val[1]))
cur1, cur2 = cur1.next, cur2.next
elif cur1.val[1] > cur2.val[1]:
res.add(cur1.val)
cur1 = cur1.next
else:
res.add(cur2.val)
cur2 = cur2.next
while cur1:
res.add(cur1.val)
cur1 = cur1.next
while cur2:
res.add(cur2.val)
cur2 = cur2.next
return res
# 测试代码
pa = LinkedList()
pa.add((3, 11))
pa.add((7, 8))
pa.add((4, 3))
pa.add((5, 0))
print('PA(x):', pa)
pb = LinkedList()
pb.add((8, 11))
pb.add((7, 8))
pb.add((10, 6))
print('PB(x):', pb)
pc = add_poly(pa, pb)
print('PC(x):', pc)
```
输出结果为:
```
PA(x): 3 -> 11 -> 7 -> 8 -> 4 -> 3 -> 5 -> None
PB(x): 8 -> 11 -> 7 -> 8 -> 10 -> 6 -> None
PC(x): 11 -> 11 -> 14 -> 8 -> 10 -> 6 -> 5 -> None
```
其中,PA(x)、PB(x)、PC(x)分别表示多项式PA、PB、PA+PB的系数和指数。