2015-07-19 109 views
0

我要编写一个菜单驱动的程序,它可以接受单词及其含义,或以字典顺序(即在字典中)显示单词列表。 我必须写的一种方法是删除方法。该分配基于链表的基本属性。我们实际上并没有使用链表类。 这是我到目前为止有:删除链接列表中的节点java

public String delete(String a) { 
    boolean found = false; 
    WordNode aux = list; 
    WordNode back = null; 
    String deleted = ""; 

    while (aux != null && !found) { 

     if (a.equalsIgnoreCase(aux.getAll().getWord())) { 
      deleted = deleted + aux.getAll().getWord(); 

      back = aux.next; 

      aux = null; 

      found = true; 
     } else { 

      back = aux; 
      aux = aux.next; 

     } 

    } 
    return deleted; 
} 

但每当我把我的主类的删除方法,然后打电话给我的toString,该列表是完整的。被删除的单词仍然在列表中。

+1

我没有看到任何实际删除回事! –

+0

你想从列表中删除字符串a吗?如果是这样,那么删除用的是什么?正如Robert Moskal所指出的那样,删除在哪里? – c0der

+1

变量'found'不是必需的,并且是多余的。 –

回答

0

所有你需要做的就是改变行(这是第12行,我认为)

back = aux.next; 

if (back == null) 
    list.next = aux.next; 
else 
    back.next = aux.next; 
1

也许这样?

public String delete(String a) { 
    WordNode aux = list; 
    WordNode back = null;   

    while (aux != null) { 

     if (a.equalsIgnoreCase(aux.getAll().getWord())) { 

     if (back != null) { 
      //change the pointer from the previous node to the one after the deleted one 
      back.next = aux.next; 
     } else { 
      //first node was found, so modify list to point his successor as the new head 
      list = aux.next; 
     } 
     return a; 
     } else { 
     back = aux; 
     aux = aux.next; 
     } 

    } 
    return ""; //no node was found 
} 

这应该符合您的合同,但我会考虑传递列表作为参数并返回指向头部的指针。