链接列表删除测试失败

时间:2014-03-20 03:46:40

标签: java list hyperlink

public void delete(int index) {
    if (index < 0 || index > count-1) {
        throw new ArrayIndexOutOfBoundsException();
    }

    Node<X> current = head;
    if (index == 0) {
        current = current.getLink();
        count--;
        return;
    }
    for (int i = 0; i < index-1; i++) {
        current = current.getLink();
    }

    current.setLink(current.getLink().getLink());
    count--;

}

@Test
public void testDeleteSeveral()
{
    LList<String> b = new LList<String>();
    b.add("hello");
    b.add("bye");
    b.add("adios");
    b.add("ciao");
    b.add("see ya");
    b.delete(0);
    assertEquals(4, b.size());
    assertEquals("ciao", b.get(0));
    assertEquals("adios", b.get(1));
    assertEquals("bye", b.get(2));
    assertEquals("hello", b.get(3));

public void add(X v)
{
    Node<X> a = new Node<X>();
    a.setValue(v);
    a.setLink(head);
    head = a;
    count++;
}

如果说assertEquals("ciao", b.get(0));,我认为它应该是&#34; ciao&#34;因为它删除了第一个节点,但错误显示为正如期望的那样#34;当我想到&#34;看到你&#34;我被删除了delete(0);我错过了什么?

编辑:我添加了添加方法

2 个答案:

答案 0 :(得分:1)

您的删除方法存在问题。

if (index == 0)
{
    current = current.getLink();
    count--;
    return;
}

它实际上并没有删除,因为&#34; head&#34;仍在引用同一个节点。尝试

if (index == 0)
{
    head = current.getLink();
    count--;
    return;
}

答案 1 :(得分:1)

您的删除方法不正确。这是一个更正版本,解释你做错了什么。

    if (index == 0)
    {
        //we're deleting the head here. You need to reassign head variable.
        //current = current.getLink(); <-- no. this doesn't change the structure.
        head = head.getLink();//here we set head to head's next. Now structure is changed.
        count--;
        return;
    }

另外,你的添加方法有点奇怪。它将项目附加到队列的前面。也许这就是你的意思,但只要知道它的书面,项目将与你添加的内容相反。所以......

list.add(1);
list.add(2);
list.add(3);

实际上会按照[3, 2, 1]而不是[1, 2, 3]包含项目。

我假设您不想要这个,并为您写一个新的添加方法。

public void add(X v)
{
    Node<X> a = new Node<X>();
    a.setValue(v);
    if(head==null)
        head = a;
    else
    {
        Node<X> tail = getTail();
        tail.setLink(a);
    }
    count++;
}
private Node<X> getTail(){
    if(head==null)
        return null;
    Node<X> current = head;
    while(current.getLink()!=null)
        current = current.getLink();
    return current;
}

这会在您的列表中添加项目。然而,结果是现在添加项目是O(n)。这在单链表中是不可避免的。

编辑:

重写了你的日常生活。我很无聊,原谅我。

public void delete(int index) {
    if (index < 0 || index > count-1) {
        throw new ArrayIndexOutOfBoundsException();
    }

    if (index == 0) {
        head = head.getLink();
    }else{
        Node<X> beforeDeletedNode = head;
        for (int i = 0; i < index-1; i++) {
            beforeDeletedNode = beforeDeletedNode.getLink();
        }
        Node<X> toDelete = beforeDeletedNode.getLink();
        beforeDeletedNode.setLink(toDelete.getLink());
    }
    count--;

}
相关问题