单链表代数和---python


# -*- coding: utf-8 -*-
"""
Created on Wed Jul  1 15:05:12 2020

@author: Melanie
"""

class Listnode():
    def __init__(self,x):
        self.data=x
        self.next=None
def add(h1,h2):
    if h1==None or h1.next==None:
        return h2
    if h2==None or h2.next==None:
        return h1
    c=0##进位
    sums=0#总和
    p1=h1.next
    p2=h2.next
    tmp=None###两个节点相加
    result=Listnode(None)
    result.next=None
    p=result
    while p1!=None and p2!=None:
        sums=p1.data+p2.data+c
        tmp=Listnode(None)
        tmp.next=None
        tmp.data=sums%10
        c=sums//10
        p.next=tmp
        p=tmp
        p1=p1.next
        p2=p2.next
    ##如果h2比h1长
    if p1 is None:
        while p2 is not None:
            tmp=Listnode(None)
            tmp.next=None
            sums=p2.data+c
            tmp.data=sums%10
            c=sums//10
            p2.next=tmp
            p2=tmp
            p2=p2.next
    if p2 is None:
        while p1 is not None:
            tmp=Listnode(None)
            tmp.next=None
            sums=p1.data+c
            tmp.data=sums%10
            c=sums//10
            p1.next=tmp
            p1=tmp
            p1=p1.next
    ####如果计算完后还有进位,则增加新的节点
    if c==1:
        tmp=Listnode(None)
        tmp.next=None
        tmp.data=1
        p.next=tmp
    return result
if __name__=="__main__":
    i=1
    head1=Listnode(None)
    head1.next=None
    head2=Listnode(None)
    head2.next=None
    tmp=None
    cur=head1
    addresult=None
   
    while i<7:
        tmp=Listnode(None)
        tmp.next=None
        tmp.data=i+2
        tmp.next=None
        cur.next=tmp
        cur=tmp
        i+=1
    cur=head2
    i=9
    while i>4:
        tmp=Listnode(None)
        tmp.data=i
        tmp.next=None
        cur.next=tmp
        cur=tmp
        i-=1
    print("head1")
    cur=head1.next
    while cur!=None:
        print(cur.data)
        cur=cur.next
    print("head2")
    cur=head2.next
    while cur!=None:
        print(cur.data)
        cur=cur.next    
    addresult=add(head1,head2)
    print("tttt")
    cur=addresult.next
    while cur!=None:
        print(cur.data)
        cur=cur.next

猜你喜欢

转载自blog.csdn.net/qq_43440040/article/details/107099076