[英]Removing first element in Linked List
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])
实际结果:正确
我的输出:错误
我试图从链接列表中删除第一个元素。 我不确定我的实现是否正确
如果要删除链接列表的第一个元素,则意味着._first
从现在._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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.