-2
我正在查找一個返回不包含特定節點的鏈接列表的函數。從功能鏈表中「刪除」一個節點
下面是一個示例實現:
Nil = None # empty node
def cons(head, tail=Nil):
""" Extends list by inserting new value. """
return (head, tail)
def head(xs):
""" Returns the frst element of a list. """
return xs[0]
def tail(xs):
""" Returns a list containing all elements except the first. """
return xs[1]
def is_empty(xs):
""" Returns True if the list contains zero elements """
return xs is Nil
def length(xs):
"""
Returns number of elements in a given list. To find the length of a list we need to scan all of its
elements, thus leading to a time complexity of O(n).
"""
if is_empty(xs):
return 0
else:
return 1 + length(tail(xs))
def concat(xs, ys):
""" Concatenates two lists. O(n) """
if is_empty(xs):
return ys
else:
return cons(head(xs), concat(tail(xs), ys))
如何才能remove_item
功能來實現?
無=沒有嚴重嗎? –
那麼?我認爲在很多情況下,「無」是一個很好的「無」值。在源代碼中使用'Nil'而不是'None'會更好地解釋。 – Alfe
@ user2799617爲什麼不呢? – Rob