(1)建立一元多项式单链表时,根据输入值来确定结束构建单链表; (2)编写一元多项式的相加程序。 (3)要编写多项式单链表的输出函数,以便能验证程序的执行结果。
时间: 2024-05-09 07:20:33 浏览: 75
c++数据结构实验:多项式相加
5星 · 资源好评率100%
以下是基于 Python 语言的一元多项式单链表的实现,包括建立、相加和输出函数:
```python
class Node:
def __init__(self, coef, exp, next=None):
self.coef = coef # 系数
self.exp = exp # 指数
self.next = next # 指向下一个节点的指针
class Polynomial:
def __init__(self):
self.head = None # 头节点
def create(self):
while True:
coef = float(input('请输入系数:'))
exp = int(input('请输入指数:'))
if coef == 0:
break
node = Node(coef, exp)
if self.head == None:
self.head = node
else:
curr = self.head
while curr.next != None:
curr = curr.next
curr.next = node
def add(self, p):
curr1 = self.head
curr2 = p.head
result = Polynomial()
curr = result.head
while curr1 != None and curr2 != None:
if curr1.exp > curr2.exp:
node = Node(curr1.coef, curr1.exp)
curr1 = curr1.next
elif curr1.exp < curr2.exp:
node = Node(curr2.coef, curr2.exp)
curr2 = curr2.next
else:
coef = curr1.coef + curr2.coef
if coef != 0:
node = Node(coef, curr1.exp)
curr1 = curr1.next
curr2 = curr2.next
if result.head == None:
result.head = node
curr = result.head
else:
curr.next = node
curr = curr.next
while curr1 != None:
node = Node(curr1.coef, curr1.exp)
curr1 = curr1.next
curr.next = node
curr = curr.next
while curr2 != None:
node = Node(curr2.coef, curr2.exp)
curr2 = curr2.next
curr.next = node
curr = curr.next
return result
def output(self):
curr = self.head
while curr != None:
print('{:.2f}x^{}'.format(curr.coef, curr.exp), end='')
curr = curr.next
if curr != None and curr.coef > 0:
print('+', end='')
print()
# 测试代码
p1 = Polynomial()
p1.create()
print('多项式1:', end='')
p1.output()
p2 = Polynomial()
p2.create()
print('多项式2:', end='')
p2.output()
p3 = p1.add(p2)
print('相加后的多项式:', end='')
p3.output()
```
在测试代码中,首先创建了两个多项式 `p1` 和 `p2`,然后调用相加函数 `add`,将相加后的结果存储在 `p3` 中,并输出三个多项式的结果。其中,输入的系数和指数可以通过 `input()` 函数获取,建议输入浮点数的系数和整数的指数,以便更精确地计算。输出函数中,格式化字符串 `{:.2f}` 表示输出两位小数的浮点数。
阅读全文