数据结构单链表实现多项式相加代码
时间: 2024-09-27 08:05:17 浏览: 37
数据结构单链表可以用于实现多项式的加法,主要是通过存储多项式的系数和指数(通常用数组表示)。以下是一个简单的Python示例,假设我们有一个节点类`Node`,用于存储一个系数和指数:
```python
class Node:
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):
new_node = Node(coefficient, exponent)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next and current.next.exponent > exponent:
current = current.next
current.next = new_node
if current.next is None or current.next.exponent == exponent:
current.next.exponent += 1
def add_polynomials(list1, list2):
sum_list = PolynomialList()
current1 = list1.head
current2 = list2.head
carry = 0
while current1 or current2:
coeff1 = carry
if current1:
coeff1 += current1.coefficient
current1 = current1.next
if current2:
coeff2 = current2.coefficient
current2 = current2.next
sum_coeff = coeff1 + coeff2
carry = sum_coeff // (exponent + 1) if sum_coeff >= 10 else 0
sum_list.add_term(sum_coeff % 10, max(current1.exponent, current2.exponent) if current1 and current2 else max(current1.exponent, 0))
if carry > 0:
sum_list.add_term(carry, 0)
return sum_list
# 示例
list1 = PolynomialList()
list1.add_term(3, 1)
list1.add_term(5, 2)
list2 = PolynomialList()
list2.add_term(2, 0)
list2.add_term(4, 1)
result = add_polynomials(list1, list2)
```
在这个例子中,`add_polynomials`函数会合并两个多项式列表,处理进位并在每个节点添加适当的系数。
阅读全文