在双向链表中更新尾部

时间:2015-02-27 01:34:17

标签: python python-3.4 doubly-linked-list

我有一个关于在我的双向链接列表类中专门为我的add_to_head方法更新self.tail的问题。我写了一个单独的函数来做这个,但我只是想知道是否有更有效的方法。 这是我的所作所为:

def add_to_head(self, data):
    '''(input)-> None
    takes any type of input and creates a node with that input as data.
    Takes that node and adds it to the front of the list
    '''
    new_node = DLLNode(data)
    if self.head == None:
        self.head = self.tail = new_node
    else:
        self.head.prev = new_node
        new_node.next = self.head
        self.head = new_node
    self.update_tail()

def update_tail(self):
    '''(DLLList)->None
    updates the tail of the DLLList
    '''
    current = self.head
    while current != None:
        current = current.next
    current = self.tail

这假设在创建此类时self.tail和self.head已设置为None。我调用这个函数的唯一一次是在调用add_to_head方法时,因为当我添加到列表的末尾时,我已经在更新尾部了。 我可以用其他方式实现这个目标吗?

0 个答案:

没有答案
相关问题