删除链接列表中的第一个元素

时间:2017-06-26 01:59:18

标签: python linked-list python-3.6

def remove(self: 'LinkedList') -> None:
    occur = self._last
    if occur!= None:
        occur = self._first
    occur._first = None

>>> lst = LinkedList([1, 2, 1, 3, 2, 1])
>>> lst.remove()
>>> lst == LinkedList([2, 1, 3, 2, 1])

实际结果: 真

我的输出: 假

我试图从链表中删除第一个元素。我不确定我的实施是否正确

1 个答案:

答案 0 :(得分:0)

如果您想删除链接列表的第一个元素,这意味着._first应该从现在开始引用列表中的第二个元素

此外,您必须检查._last元素是否为._first元素。如果是这种情况,您还必须将._last设置为None,因为在这种情况下,列表只包含一个元素。

所以你可以这样做:

def remove_head (self: 'LinkedList') -> None:
    # check if the list is not empty
    if self._first is not None:
        # check if first and last refer to the same node
        if self._last is self._first:
            # if so the list contains one node, so set _last to None
            self._last = None
        # update the pointer to the _first element to advance one hop
        self._first = self._first._next

我在此假设对节点中下一个节点的引用称为_next。但你可以很容易地改变它。您还可以使用更具描述性的名称来命名您的函数,例如remove_head