2014-10-28 31 views
-1

我與鏈表和類幾乎只在C++中工作,所以我無法得到這個工作。第一類應該有變量名稱和下一個,init函數,兩個getter函數和兩個setter函數。第二類(Line)應該有一個初始化函數和一個添加函數,將項添加到鏈表的末尾。我似乎無法讓我的添加功能工作。任何幫助表示讚賞。使用Python中的鏈表來模擬排隊

這是我到目前爲止的代碼。

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: 
+4

什麼*「可以」 t似乎得到[它]的工作「*的意思,確切地說?你似乎還沒有完成它的實施...... – jonrsharpe 2014-10-28 16:25:42

+0

你能描述你嘗試添加一個人時看到的行爲嗎?發生什麼事與你預期會發生什麼? python中的 – Mike 2014-10-28 16:29:03

+1

,你可能不需要像在c中一樣實現這個。你可能只是在'Line()'中繼承'list'對象,所以你繼承了它的'append()'和其他列表方法。然後,只需追加和彈出它就可以了。 – TehTris 2014-10-28 16:29:43

回答

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 

是一種選擇

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 
+0

我懷疑列表遍歷是作業+1的一部分,因爲這是一個更好的解決方案 – 2014-10-28 16:56:36