Java 删除方法不使用';t删除具有特定名称的节点

Java 删除方法不使用';t删除具有特定名称的节点,java,singly-linked-list,Java,Singly Linked List,大家好,我正在尝试删除具有特定名称的节点。但显然没有删除节点,它只是打印出所有内容。包含该名称的节点不会被删除。我写了我的链表,除了删除一个具有特定名称的节点外,其他一切都正常工作。以下是我删除特定名称的方法: public void remove(String name) { if(!this.isEmpty()) { LinkedList current = first; //LinkedList prev = null; w

大家好,我正在尝试删除具有特定名称的节点。但显然没有删除节点,它只是打印出所有内容。包含该名称的节点不会被删除。我写了我的链表,除了删除一个具有特定名称的节点外,其他一切都正常工作。以下是我删除特定名称的方法:

 public void remove(String name)
{
    if(!this.isEmpty())
    {
        LinkedList current = first;
        //LinkedList prev = null;
        while(current!=null)
        {
            //prev = current;
            if(current.name.equals(name))
            {
                current = current.getNext();
                count--;
                break;
            }
            current=current.getNext();
        }
    }
    else
    {
        System.out.println("Cannot search an empty list");
    }
}
主要方法:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Link a = new Link();
     a.addEnd("Tom"); //adds at the end of list
     a.addEnd("Joe");
     a.addEnd("Gary");
     a.add("Kim"); //adds at the beginning of the list
     a.addIndex("Nene", 1); //adds to an index position.
     a.remove("Kim"); //calls the method to remove the name kim but doesn't delete it.still displays kim on the console.
       a.display();
}
}

我认为一个很小的调整将使这个工作。我假设您正在扩展内置Java LinkedList:

在你的条件:

if(!this.isEmpty())
{
    LinkedList current = first;
    //LinkedList prev = null;
    while(current!=null)
    {
        //prev = current;
        if(current.name.equals(name))
        {
            // Right here you need to do a this.remove(current.getId)
            current = current.getNext();
            count--;
            break;
        }
        current=current.getNext();
    }
}
您正在减少计数,但实际上并没有从列表中删除元素。Java的内置LinkedList有一个remove by ID方法:。因为您已经获得了与名称匹配的元素,所以您应该能够将该元素ID的索引传递给remove方法

如果您不是将此作为现有方法的扩展,那么我建议您使用前瞻。了解你的当前和下一个目标。这样您就可以遵循以下逻辑(请原谅我的伪代码):


您需要上一个节点来删除当前节点。或者,您可以将所有数据从下一个节点移动到当前节点,但如果它是链接列表中的最后一个节点,则此操作将不起作用。您的代码中没有试图删除节点的行,这就是问题所在。如果名称匹配或不匹配,则执行
current=current.getNext()
。您应该至少更改链接列表中的一个链接。
If next matches, do next.getNext()
If next.getNext() returns null,
    then pop the last value off the list (current.setNext(null))
Else
    do current.setNext(next.getNext())