我正在尝试编写一个程序来添加两个整数列表。以下是我的实施:

时间:2016-12-23 08:27:29

标签: python-3.x data-structures linked-list

class Solution:

def addTwoListInt(self,l1,l2):
    if l1==None:
        return l2

    if l2==None:
        return l1

    res = None


    len1 = 0
    #head1=l1

    while l1!=None:
        len1+=1
        head1=head1.next

    len2 = 0
    #head2=l2

    while l2!=None:
        len2+=1
        head2=head2.next

    if len1<len2:
        longer = l2
        shorter = l1
    else:
        longer = l1
        shorter = l2

    carry = 0


    while shorter!=None:
        val = shorter.data + longer.data + carry
        carry = val//10
        val -= carry*10

        if res==None:
            res = Node(val)
            result = res
        else:
            res.next = Node(val)
            res = res.next

        shorter = shorter.next
        longer = longer.next

    while longer!=None:
        val = longer.data + carry
        carry = val//10
        val -= carry*10

        res.next = Node(val)
        res = res.next

        longer = longer.next

    if carry!=0:
        res.next = Node(carry)
        res=res.next

    return result

如果我不使用head1和head2作为列表标题的l1和l2,则函数返回UnbondLocalError,表示结果在赋值之前已被引用,如果我将l1和l2指定为head1和head2,则它可以工作用它们来处理代码。如果我不在函数中本地分配它们,为什么它不起作用,我想知道发生了什么。

1 个答案:

答案 0 :(得分:0)

如果没有head1head2,您就拥有:

len1 = 0
while l1!=None:
    len1+=1
    l1=l1.next
// when the loop exits, l1==None

len2 = 0
while l2!=None:
    len2+=1
    l2=l2.next
// when the loop exits, l2 == None

此时,l1l2都是None。因此,您最终会为Noneshorter分配longer。因此,您的所有循环均未输入,并且永远不会为res分配值。