【问题标题】:Removing first element in Linked List删除链表中的第一个元素
【发布时间】:2017-06-26 10:12:42
【问题描述】:
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])

实际结果: 是的

我的输出: 假的

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

【问题讨论】:

  • 抱歉,请问您有什么问题?
  • 我更新了我的问题
  • 但是您只设置了occur的引用,这是一个本地引用。
  • @WillemVanOnsem 你是什么意思
  • @TheGamer:通过设置occur = self._last,对occurreference 的更改将不会 反映到self._last 本身。

标签: python linked-list python-3.6


【解决方案1】:

如果你想移除链表的第一个元素,这意味着._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

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多