1 回答

TA贡献1796条经验 获得超4个赞
尝试这个:
class List:
""" This implements a list using `Node` for its elements """
class Node:
""" A node consists of a value (val) and a next-ptr (lnk) """
def __init__(self, val, lnk=None):
self.val = val
self.lnk = lnk
def __init__(self, root=None):
self.root = root
def append(self, val):
""" Appends a node with value `val` to the end of the list.
"""
if self.root is None:
self.root = List.Node(val)
else:
curr = self.root
while curr.lnk:
curr = curr.lnk
curr.lnk = List.Node(val)
# Test for List.append(val)
if __name__ == '__main__':
l = List()
l.append('one')
l.append('two')
l.append('three')
print(l.root.val, l.root.lnk.val, l.root.lnk.lnk.val)
print('End of Tests.')
输出:
one two three
End of Tests.
添加回答
举报