删除方法不会删除具有特定名称的节点

时间:2014-11-21 00:10:51

标签: java singly-linked-list

大家好我想删除一个具有特定名称的节点。但显然没有删除它只打印出一切的节点。包含该名称的节点不会被删除。我编写了我的链表,除了删除具有特定名称的节点外,一切正常。以下是我删除特定名称的方法:

 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();
}
}

1 个答案:

答案 0 :(得分:1)

我认为一个非常小的调整将使这个工作。我假设你正在扩展内置的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有一个按ID删除的方法:LinkedList.remove。由于您拥有与名称匹配的元素,因此您应该能够将该元素ID的索引传递给remove方法。

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

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())