【发布时间】:2013-11-17 06:34:24
【问题描述】:
到目前为止,这就是我现在所拥有的
class X:
def __init__(self,value,next=None):
self.value = value
self.next = next
def linkedlist(l):
if l == []:
return None
beg = end = X(l[0])
for v in l[1:]:
end.next = X(v)
end = end.next
return beg
lst1 = linkedlist(['a', 'b', 'c''])
lst2 = linkedlist(['a', 'b', 'c'])
lst3 = linkedlist(['c', 'a', 'b'])
我正在尝试创建一个递归函数来确定两个链表 lst 1 和 lst 2 是否相同。如果是,则返回 True,否则返回 False。
def is_same(lst1, lst2):
if lst1.next == None or lst2.next == None:
return None
else:
if lst1.next == lst2.next:
return X(is_same(lst1.next, lst2.next))
else:
return True
我知道我的递归函数是错误的,但我遇到了麻烦,因为它一直给我错误。每次我输入时,“is_same”函数都会返回 True:
is_same(lst1, lst2)
is_same(lst1, lst3) # This should be False
【问题讨论】: