如何删除链表中的第一个节点?

新手上路,请多包涵

Sup 伙计们,所以我在我的链表类中复习了一些方法,当从链表中删除节点时我遇到了一个逻辑错误。当我在 removeLast() 方法中也遇到错误时,我正在处理我的 removeFirst() 方法。问题是两者都删除了列表中的最后一项。不知道为什么,但这是我的代码。

删除第一个节点

public T removeFirst() throws EmptyCollectionException
{
 // Checking to see if the List is empty or not
    if ( isEmpty() )
        throw new EmptyCollectionException("LinkedList");

    Node < T > temp  = contents;

    T  next = contents.getNext().getItem();

    contents = new Node ( next, contents );
    count--;

    return temp.getItem();
}

删除最后一个节点

public T removeLast() // fixed
{
 // Checking to see if the List is empty or not
    if (isEmpty())
        throw new EmptyCollectionException("LinkedList");

    // Node<T> temp = contents;
    Node<T> current = contents;
    Node<T> prev = null;

    while (current.getNext() != null)
    {
        prev = current;
        current = current.getNext();
    }

    prev.setNext(null);

    count--;

    return current.getItem();

}

我查看了已经发布的问题,但似乎找不到我正在寻找的答案。

我知道一个节点至少有两个值

一个保存数据,另一个保存对下一个节点的引用

这就是我认为第一个正在发生的事情。但是当我一个接一个地调用这些方法时,它们都摆脱了最后一个节点。 Idk 我会查看我的代码并在必要时更新此问题。但是你们能不能看出我哪里出错了,并指出我正确的方向。谢谢你。

原文由 user2124140 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 538
2 个回答

如果你有一个列表 A->B->C,A 是列表的头部(“内容”),为了删除它,你只需将指针指向 B,即列表中的下一个节点:

 public T removeFirst() throws EmptyCollectionException {
    // Checking to see if the List is empty or not
    if ( isEmpty() )
        throw new EmptyCollectionException("LinkedList");

    Node<T> first = contents;

    contents = contents.getNext();
    count--;

    return first.getItem();
}

由于您还需要返回与第一个节点关联的数据,因此您需要保留对它的临时引用。 (我称之为 first

原文由 ValarDohaeris 发布,翻译遵循 CC BY-SA 3.0 许可协议

public void removeFirst() {
        if (head == null)
              return;
        else {
              if (head == tail) {
                    head = null;
                    tail = null;
              } else {
                    head = head.next;
              }
        }
  }

原文由 gifpif 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题