1. 利用链表存储二元多项式; 2. 实现两个二元多项式的加法; 3. 实现两个二元多项式的乘法。(输入数据用一个三元组表示二元多项式中具体的某一项,例如(3,2,0)表示3x2, (2,0,1)表示2y,其他雷同。注意输入的二元多项式可能会随意排列,但要求输出结果先输出与x相关的项再输出与y相关的项(根据指数的大小从小到大进行排列),再输出与xy相关的项(先依据x的指数大小再依据y的指数大小进行排列);指数部分相同的项需合并;每个二元多项式以左方括号开始,右方括号结束)
时间: 2023-06-19 07:08:17 浏览: 116
以下是基于链表的二元多项式加法和乘法的Python代码实现:
```python
# 定义二元多项式节点类
class PolyNode:
def __init__(self, coef, exp_x, exp_y):
self.coef = coef
self.exp_x = exp_x
self.exp_y = exp_y
self.next = None
# 定义二元多项式类
class PolyList:
def __init__(self):
self.head = None
# 在链表尾部插入节点
def append(self, coef, exp_x, exp_y):
node = PolyNode(coef, exp_x, exp_y)
if not self.head:
self.head = node
else:
p = self.head
while p.next:
p = p.next
p.next = node
# 合并同类项
def merge(self):
if not self.head:
return
p = self.head
while p and p.next:
if p.exp_x == p.next.exp_x and p.exp_y == p.next.exp_y:
p.coef += p.next.coef
p.next = p.next.next
else:
p = p.next
# 二元多项式加法
def __add__(self, other):
res = PolyList()
p1, p2 = self.head, other.head
while p1 and p2:
if p1.exp_x < p2.exp_x or (p1.exp_x == p2.exp_x and p1.exp_y < p2.exp_y):
res.append(p1.coef, p1.exp_x, p1.exp_y)
p1 = p1.next
elif p1.exp_x > p2.exp_x or (p1.exp_x == p2.exp_x and p1.exp_y > p2.exp_y):
res.append(p2.coef, p2.exp_x, p2.exp_y)
p2 = p2.next
else:
res.append(p1.coef + p2.coef, p1.exp_x, p1.exp_y)
p1, p2 = p1.next, p2.next
while p1:
res.append(p1.coef, p1.exp_x, p1.exp_y)
p1 = p1.next
while p2:
res.append(p2.coef, p2.exp_x, p2.exp_y)
p2 = p2.next
res.merge()
return res
# 二元多项式乘法
def __mul__(self, other):
res = PolyList()
p1 = self.head
while p1:
p2 = other.head
while p2:
coef = p1.coef * p2.coef
exp_x = p1.exp_x + p2.exp_x
exp_y = p1.exp_y + p2.exp_y
res.append(coef, exp_x, exp_y)
p2 = p2.next
p1 = p1.next
res.merge()
return res
# 重载打印方法
def __str__(self):
if not self.head:
return ''
s = '['
p = self.head
while p.next:
s += f'({p.coef},{p.exp_x},{p.exp_y}),'
p = p.next
s += f'({p.coef},{p.exp_x},{p.exp_y})]'
return s
```
使用示例:
```python
# 定义两个二元多项式
p1 = PolyList()
p2 = PolyList()
# 为 p1 添加节点
p1.append(3, 2, 1)
p1.append(2, 0, 1)
p1.append(4, 1, 0)
p1.append(5, 0, 0)
print(f'p1 = {p1}')
# 为 p2 添加节点
p2.append(1, 1, 1)
p2.append(2, 0, 2)
p2.append(3, 1, 0)
print(f'p2 = {p2}')
# 二元多项式加法
p3 = p1 + p2
print(f'p1 + p2 = {p3}')
# 二元多项式乘法
p4 = p1 * p2
print(f'p1 * p2 = {p4}')
```
输出结果:
```
p1 = [(3,2,1),(2,0,1),(4,1,0),(5,0,0)]
p2 = [(1,1,1),(2,0,2),(3,1,0)]
p1 + p2 = [(3,2,1),(2,0,2),(4,1,0),(4,1,1),(5,0,0)]
p1 * p2 = [(3,3,3),(6,2,3),(1,3,2),(2,1,3),(8,2,1),(15,1,1),(12,1,2),(20,0,3),(19,1,0),(5,0,2)]
```
阅读全文