繁体   English   中英

从Java中的链表中删除节点

[英]Remove node from a linked list in java

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

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

或者也许我只是不了解编码概念,我的老师想要的实际上不是“删除”节点,只是将当前节点重定向到当前节点,然后再重定向到当前节点,有人可以帮我吗?

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

删除节点的“跳过”必须位于匹配的if语句中。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM