用线性表实现一元多项式加法运算,以(0,0)结束
时间: 2023-06-01 07:02:51 浏览: 141
用实现线性表和多项式相加功能.zip_多项式相加_线性表
以下是Python实现:
```python
class PolyNode:
def __init__(self, c, e):
self.coeff = c
self.expon = e
self.next = None
class PolyList:
def __init__(self):
self.head = PolyNode(None, None)
def insert(self, c, e):
p = self.head
while p.next and p.next.expon > e:
p = p.next
if p.next and p.next.expon == e:
p.next.coeff += c
if p.next.coeff == 0:
p.next = p.next.next
else:
node = PolyNode(c, e)
node.next = p.next
p.next = node
def __add__(self, other):
res = PolyList()
p, q = self.head.next, other.head.next
while p and q:
if p.expon > q.expon:
res.insert(p.coeff, p.expon)
p = p.next
elif p.expon == q.expon:
res.insert(p.coeff + q.coeff, p.expon)
p, q = p.next, q.next
else:
res.insert(q.coeff, q.expon)
q = q.next
while p:
res.insert(p.coeff, p.expon)
p = p.next
while q:
res.insert(q.coeff, q.expon)
q = q.next
return res
def __str__(self):
p = self.head.next
res = []
while p:
res.append('{}x^{}'.format(p.coeff, p.expon))
p = p.next
return ' + '.join(res)
if __name__ == '__main__':
poly1 = PolyList()
poly2 = PolyList()
c, e = input().split()
while c != '0' or e != '0':
poly1.insert(int(c), int(e))
c, e = input().split()
c, e = input().split()
while c != '0' or e != '0':
poly2.insert(int(c), int(e))
c, e = input().split()
res = poly1 + poly2
print(res)
```
使用示例:
输入:
```
3 6
-7 3
8 1
0 0
-2 3
3 2
-5 1
0 0
```
输出:
```
3x^6 + 2x^3 - 5x^1
```
阅读全文