02-线性结构2 一元多项式的乘法与加法运算(python3)

搜到一篇也是讲这个的,但是那篇并没有完全用到单向链表的方法,所以研究了一下,写了一个是完全用单向链表的方法:

其实应该有更优雅的删除整个单向列表的方法,比如头设为none,可能会改进下?

L1=list(map(int,input().split()))
L2=list(map(int,input().split()))
#节点
class Node:
    def __init__(self,coef,exp):
        self.coef=coef
        self.exp=exp
        self.next=None
#单链表
class List:
    def __init__(self,node=None):
        self.__head=node
    #为了访问私有类
    def gethead(self):
        return self.__head
    
    def travel(self):
        cur1=self.__head
        cur2=self.__head
        if cur1.next !=None:
            cur1=cur1.next
        else:
            print(cur2.coef,cur2.exp,end="")
            return
        while cur1.next !=None:
            print(cur2.coef,cur2.exp,end=" ")
            cur1=cur1.next
            cur2=cur2.next
        
        print(cur2.coef,cur2.exp,end=" ")
        cur2=cur2.next
        print(cur2.coef,cur2.exp,end="")
        
#add item in the tail
    def append(self,coef,exp):
        node =Node(coef,exp)
        if self.__head==None:
            self.__head=node
        else:
            cur=self.__head
            while cur.next !=None:
                cur=cur.next
            cur.next=node

def addl(l1,l2):
    p1=l1.gethead()
    p2=l2.gethead()
    l3=List()
    while (p1 is not None) & (p2 is not None):
        if(p1.exp>p2.exp):
            l3.append(p1.coef,p1.exp)
            p1=p1.next
        elif(p1.exp

 

你可能感兴趣的:(数据结构)