我几乎只在c++中使用链表和类,所以我很难实现这一点。第一个类应该有变量名称,接下来是一个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:
或者只跟踪尾部,以避免每次添加内容时遍历整个列表:
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
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
是的一个选项