从java中的链接列表中删除节点

时间:2014-04-08 16:13:49

标签: java linked-list

我正在使用LinkedList创建一个字典类型的程序,但我不能使用LinkedList实用程序,我必须创建自己的,所以我不能使用任何这些方法,我必须删除一个节点,我可以为我的生活弄明白了。我可以在纸上完成它,但在代码中,它要么删除之前的所有内容,要么只是冻结等等。这是我到目前为止删除方法的内容:

void delete(String w)
{ 
        WordMeaningNode temp = list;
        WordMeaningNode current = list;
        WordMeaningNode back = null;
        boolean found = false;
        while(current != null && !found)
        {
            if( current.WordMeaning.getTitle().equals(w))
            {
                found = true;
                System.out.println("found it!");
            }
            else
            {
                back = current;
                current = current.next;
            }
         temp = current.next; //this is where the problem starts
         back.next = temp;
         }
}

以下是我如何称呼它:

String delWord = JOptionPane.showInputDialog("Enter word to be deleted");
                WordMeaning.delete(delWord);

或者我只是不理解编码概念,我的老师想要的实际上并不是“删除”节点,只是将当前节点重定向到当前节点之后,任何人都可以帮助我吗? / p>

2 个答案:

答案 0 :(得分:0)

public boolean deleteMiddleNode(Node middleNode)
{
//error check:
if  (middleNode  ==  null  ||  middleNode.next  ==  null)
return false;

/*
middleNode is x in our example data above, but
is now changed to hold the data of node y:
*/
middleNode.data = middleNode.next.data;

/*tempNode now holds node z if following
the example above:  */
Node tempNode = middleNode.next.next;
//delete the old node Y from example above
delete(middleNode.next);
/*reset pointer so that the new "y" points
  to z
*/
middleNode.next = tempNode;
}

答案 1 :(得分:0)

"跳过"删除节点需要在匹配的if-statment中。

假设1:变量' list'始终指向列表的第一个元素。

假设2:该清单不是循环的。否则算法可能不会终止。

但除了下面的实现之外,你还必须处理边界情况(空列表,带有一个元素的列表,如果删除第一个条目)。

 void delete(String w) { 
    WordMeaningNode current = list;
    WordMeaningNode back = null;
    boolean found = false;
    while(current != null && !found)
    {
        if( current.WordMeaning.getTitle().equals(w))
        {
            found = true;
            System.out.println("found it!");
            back.next = current.next;
        }
        else
        {
            back = current;
            current = current.next;
        }
     }
 }
相关问题