编写一个程序用单链表存储多项式,并实现两个一元多项式A与B相加的函数。A,B刚开始是无序的,A与B之和按降序排列。例如: 多项式A: 1.2X^0



import sys
class equation:
    def __init__(self):
        self.coef=0
        self.exp=0
        self.next=None
def create_link(data,s):
    j=0
    for i in range(s):
        newnode=equation()
        if not newnode:
            print('Error!!内存分配失败!!')
            sys.exit(0)
        if i==0:
            newnode.coef=data[j]
            j= j + 1
            newnode.exp=data[j]
            newnode.next=None
            head=newnode
            ptr=head
            j+=1
        elif i !=0:
            newnode.coef=data[j]
            j = j + 1
            newnode.exp=data[j]
            newnode.next=None
            ptr.next=newnode
            ptr=newnode
            j+=1
    return head
def print_link(head):
    while head.coef != 0 and head.coef != None and head.exp != None:
        head = head.next
    head = head.next
    head = head.next
    print('%.1f %d' % (head.coef, head.exp))





''' while head!=None:
        if head.coef!=0 and head.coef!=None and head.exp!=None :
            print('%.1fX^%d'%(head.coef,head.exp))

        head=head.next
    print()
'''

def sum_link(a,b,f):
    i=0
    plus=[None]*f*2
    #print(plus)
    while a!=None:
        if a.exp==b.exp:
            plus[i]=a.coef+b.coef
            i=i+1
            plus[i] = a.exp
            a=a.next
            b=b.next
            i=i+1
        elif b.exp>a.exp:
            plus[i]=a.coef
            i = i + 1
            plus[i ] = a.exp
            a=a.next
            i=i+1
        elif a.exp>b.exp:
            plus[i]=b.coef
            i = i + 1
            plus[i ] = b.exp
            b=b.next
            i=i+1
    while b != None and i<=2*f :
        plus[i] = b.coef
        i = i + 1
        plus[i] = b.exp
        b = b.next
        i = i + 1
   # print(plus)
    return create_link(plus,f)
def main():
    a =list(map(float,input().strip().split()))
    c=len(a)//2
   # print(c)
    b = list(map(float, input().strip().split()))
    d= len(b) // 2
    #print(d)
    if  c>=d:
        f=c
    else: f=d
    a1=create_link(a,c)
    b1=create_link(b,d)
    #print_link(a1)
   # print_link(b1)
    print_link(sum_link(a1,b1,f))
main()

你可能感兴趣的:(编写一个程序用单链表存储多项式,并实现两个一元多项式A与B相加的函数。A,B刚开始是无序的,A与B之和按降序排列。例如: 多项式A: 1.2X^0)