删除linklist java中的节点

时间:2015-07-19 16:18:46

标签: java

我要写一个菜单驱动的程序,要么接受单词及其含义,要么按字典顺序显示单词列表(即在字典中)。 我必须编写的一种方法是删除方法。赋值基于linkedlist的基本属性。我们实际上并没有使用linkedlist类。 这就是我到目前为止所做的:

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

但每当我在主类中调用delete方法然后调用我的toString时,列表就完好无损了。删除的单词仍在列表中。

2 个答案:

答案 0 :(得分: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
}

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

答案 1 :(得分:0)

你所要做的就是改变这条线(我想是第12行)

back = aux.next;

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