我几乎只使用c ++来处理链接列表和类,所以我无法让它工作。第一个类应该有变量name和next,一个init函数,两个getter函数和两个setter函数。第二个类(Line)应该有一个init函数和一个add项,它将项添加到链表的末尾。我似乎无法使我的添加功能起作用。任何帮助表示赞赏。
这是我到目前为止的代码。
class PersonList():
"""
The class to represent the node in a linked list of people. It takes the variables:
name, which represents the person's name, and next_person, which links the next
person in the linked list.
"""
def __init__(self, name = None, next_ = None):
self.__name = name
self.__next = next_
def getName(self):
return self.__name
def getNext(self):
return self.__next
def setName(self, new_name):
self.__name = new_name
def setNext(self, new_person):
self.__next = new_person
def __str__(self):
return (self.__name)
def printlist(node):
next_node = node.getNext()
while next_node != None:
next_node = node.getNext()
print (node)
node = node.getNext()
class Line():
""" The class that represents the line of people as the linked list. Takes the variable
head, that denotes the first person in the line
"""
def __init__(self, head = None):
self.head = None
def add(self, name):
if self.head == None:
self.head = PersonList(name)
else:
答案 0 :(得分:1)
或者只是跟踪尾部以避免每次想要添加内容时遍历整个列表:
class Line():
""" The class that represents the line of people as the linked list. Takes the variable
head, that denotes the first person in the line
"""
def __init__(self, head = None):
self.head = None
self.tail = None
def add(self, name):
tmp = PersonList(name)
if self.head == None:
self.head = tmp
self.tail = tmp
else:
self.tail.next = tmp
self.tail = tmp
答案 1 :(得分:0)
def add(self, name):
if self.head == None:
self.head = PersonList(name)
else:
tmp = self.head
while tmp._next is not None: #while we are not at the end of the line
tmp = tmp._next
#end of line
tmp._next = PersonList(name) #get in line at the end
是一个选项