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

问题描述 投票:1回答:4

Sup人所以我在我的Linked List类中查看了一些我的方法,当从链表中删除一个节点时,我遇到了一个逻辑错误。当我在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我会查看我的代码并在必要时更新此问题。但你们能看到我出错的地方,并指出我正确的方向。谢谢。

java loops linked-list nodes
4个回答
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


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

0
投票

我认为您需要将头节点添加到链表类中以定义列表的第一个节点。

public void deleteFront()
{
 if (head!=null)
 head = head.Next;
}

0
投票
public T removeFirst() throws EmptyCollectionException {
 if (isEmpty())
    throw new EmptyCollectionException("LinkedList");

Node < T > temp  = contents;

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

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



  return temp.getItem();
}

在这个方法中注释最后三个语句。然后添加以下三行

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

删除最后一个节点:它看起来很好。

© www.soinside.com 2019 - 2024. All rights reserved.