构造两个按指数递增的有序链表,实现两个一元多项式相加的代码
时间: 2024-11-03 12:13:17 浏览: 11
在构建一个支持指数项的有序链表来表示一元多项式,并实现在链表上进行多项式的加法操作,首先需要定义一个节点结构,包含系数和指数两个字段。然后,我们可以创建两个这样的链表,分别表示两个多项式。当需要将它们相加时,我们需要遍历这两个链表,对应位置的系数相加,同时取较大的指数作为新节点的指数。
以下是使用Python的一种简单实现:
```python
class PolynomialNode:
def __init__(self, coefficient=0, exponent=0):
self.coefficient = coefficient
self.exponent = exponent
self.next = None
class PolynomialList:
def __init__(self):
self.head = None
def add_term(self, coefficient, exponent):
if not self.head:
self.head = PolynomialNode(coefficient, exponent)
else:
current = self.head
while current.next and current.next.exponent >= exponent:
current = current.next
new_node = PolynomialNode(coefficient, exponent)
new_node.next = current.next
current.next = new_node
# 实现多项式加法
def add_poly_lists(list1, list2):
result = PolynomialList()
current1 = list1.head
current2 = list2.head
carry = 0
while current1 or current2:
coef1 = (current1 and current1.coefficient) or 0
coef2 = (current2 and current2.coefficient) or 0
total_coeff = coef1 + coef2 + carry
carry = total_coeff // (10 ** max(current1.exponent if current1 else 0, current2.exponent if current2 else 0))
total_coeff %= 10 ** max(current1.exponent if current1 else 0, current2.exponent if current2 else 0)
result.add_term(total_coeff, max(current1.exponent if current1 else 0, current2.exponent if current2 else 0))
if current1:
current1 = current1.next
if current2:
current2 = current2.next
# 如果最后还有进位,则添加一个零次项
if carry > 0:
result.add_term(carry, 0)
return result
# 示例:
list1 = PolynomialList()
list1.add_term(2, 2) # 2x^2
list1.add_term(4, 1) # 4x
list2 = PolynomialList()
list2.add_term(5, 1) # 5x
list2.add_term(6, 0)
阅读全文