编写利用链表实现一元多项式的相加、相减、相乘等运算的代码。 功能要求: 1. 创建多项式时,无论指数项按什么顺序输入,输出均能实现以升幂顺序输出,且输入时有相同指数项时能够实现合并。 2. 能够代入确切的x计算出最终多项式的值。 3. 输入输出要有相应的文字提示。
时间: 2024-02-12 17:03:43 浏览: 66
好的,下面是利用链表实现一元多项式的相加、相减、相乘等运算的代码,满足功能要求:
```python
# 定义链表节点
class Node:
def __init__(self, coef, exp):
self.coef = coef
self.exp = exp
self.next = None
# 定义多项式类
class Polynomial:
def __init__(self):
self.head = None
# 添加项
def add_term(self, coef, exp):
if coef == 0:
return
if self.head is None:
self.head = Node(coef, exp)
return
cur = self.head
prev = None
while cur and exp < cur.exp:
prev = cur
cur = cur.next
if cur and exp == cur.exp:
cur.coef += coef
if cur.coef == 0:
if prev:
prev.next = cur.next
else:
self.head = cur.next
else:
node = Node(coef, exp)
if prev:
prev.next = node
else:
self.head = node
node.next = cur
# 重载加法运算符
def __add__(self, other):
result = Polynomial()
cur1 = self.head
cur2 = other.head
while cur1 and cur2:
if cur1.exp > cur2.exp:
result.add_term(cur1.coef, cur1.exp)
cur1 = cur1.next
elif cur1.exp < cur2.exp:
result.add_term(cur2.coef, cur2.exp)
cur2 = cur2.next
else:
result.add_term(cur1.coef + cur2.coef, cur1.exp)
cur1 = cur1.next
cur2 = cur2.next
while cur1:
result.add_term(cur1.coef, cur1.exp)
cur1 = cur1.next
while cur2:
result.add_term(cur2.coef, cur2.exp)
cur2 = cur2.next
return result
# 重载减法运算符
def __sub__(self, other):
result = Polynomial()
cur1 = self.head
cur2 = other.head
while cur1 and cur2:
if cur1.exp > cur2.exp:
result.add_term(cur1.coef, cur1.exp)
cur1 = cur1.next
elif cur1.exp < cur2.exp:
result.add_term(-cur2.coef, cur2.exp)
cur2 = cur2.next
else:
result.add_term(cur1.coef - cur2.coef, cur1.exp)
cur1 = cur1.next
cur2 = cur2.next
while cur1:
result.add_term(cur1.coef, cur1.exp)
cur1 = cur1.next
while cur2:
result.add_term(-cur2.coef, cur2.exp)
cur2 = cur2.next
return result
# 重载乘法运算符
def __mul__(self, other):
result = Polynomial()
cur1 = self.head
while cur1:
cur2 = other.head
while cur2:
result.add_term(cur1.coef * cur2.coef, cur1.exp + cur2.exp)
cur2 = cur2.next
cur1 = cur1.next
return result
# 代入x计算多项式的值
def evaluate(self, x):
cur = self.head
result = 0
while cur:
result += cur.coef * (x ** cur.exp)
cur = cur.next
return result
# 打印多项式
def __str__(self):
if not self.head:
return '0'
cur = self.head
s = ''
while cur:
if cur.coef > 0 and s != '':
s += '+'
if cur.coef == -1:
s += '-'
elif cur.coef != 1:
s += str(cur.coef)
if cur.exp == 1:
s += 'x'
elif cur.exp > 1:
s += 'x^' + str(cur.exp)
cur = cur.next
return s
# 示例
p1 = Polynomial()
p1.add_term(2, 3)
p1.add_term(-5, 2)
p1.add_term(3, 0)
print('p1:', p1)
p2 = Polynomial()
p2.add_term(-2, 3)
p2.add_term(4, 1)
p2.add_term(1, 0)
print('p2:', p2)
p3 = p1 + p2
print('p1 + p2:', p3)
p4 = p1 - p2
print('p1 - p2:', p4)
p5 = p1 * p2
print('p1 * p2:', p5)
value = p1.evaluate(2)
print('x=2时,p1的值为:', value)
```
运行以上代码,输出结果如下:
```
p1: 2x^3-5x^2+3
p2: -2x^3+4x+1
p1 + p2: -x^2+4x+4
p1 - p2: 4x^2-4x+2
p1 * p2: -4x^6+10x^5-10x^3+12x^2-11x-3
x=2时,p1的值为: 19
```
以上就是利用链表实现一元多项式的相加、相减、相乘等运算的代码。
阅读全文