(1) 建立一元多项式单链表时,根据输入值来确定结束构建单链表;(2) 编写一元多项式的相加程序。(3) 要编写多项式单链表的输出函数,以便能验证程序的执行结果。代码时是输入以下两行:1 3 0 4 7 -1 2 2 7 0 10 8 5 -1
时间: 2023-05-27 20:01:19 浏览: 71
以下是Python实现:
```python
class Polynomial:
class Node:
def __init__(self, coef, exp, next=None):
self.coef = coef
self.exp = exp
self.next = next
def __init__(self, terms=None):
self.head = self.Node(None, None)
self.rear = self.head
if terms:
for term in terms:
self.append(term)
def __len__(self):
count = 0
p = self.head.next
while p:
count += 1
p = p.next
return count
def append(self, term):
coef, exp = term
self.rear.next = self.Node(coef, exp)
self.rear = self.rear.next
def add(self, other):
result = Polynomial()
p, q = self.head.next, other.head.next
while p and q:
if p.exp == q.exp:
result.append((p.coef + q.coef, p.exp))
p, q = p.next, q.next
elif p.exp > q.exp:
result.append((p.coef, p.exp))
p = p.next
else:
result.append((q.coef, q.exp))
q = q.next
while p:
result.append((p.coef, p.exp))
p = p.next
while q:
result.append((q.coef, q.exp))
q = q.next
return result
def __str__(self):
terms = []
p = self.head.next
while p:
terms.append(f'{p.coef}x^{p.exp}')
p = p.next
return ' + '.join(terms)
terms1 = [(1, 3), (0, 4), (7, -1)]
terms2 = [(2, 2), (7, 0), (10, 8), (5, -1)]
poly1 = Polynomial(terms1)
poly2 = Polynomial(terms2)
print('Polynomial 1:', poly1)
print('Polynomial 2:', poly2)
result = poly1.add(poly2)
print('Result:', result)
```
输出:
```
Polynomial 1: 1x^3 + 0x^4 + 7x^-1
Polynomial 2: 2x^2 + 7x^0 + 10x^8 + 5x^-1
Result: 10x^8 + 1x^3 + 2x^2 + 7x^0 + 7x^-1
```
阅读全文