如何在链接列表中删除特定单词(节点)



我有问题。我想删除一个节点,但是当我打印列表时它仍然存在。我不知道问题是什么。

public void REMOVEWORD(String word) {
    //declare and initialize a help pointer 
    Word helpPtr = head;
    while (helpPtr.getNext() != null) {
        if (helpPtr.getNext().getWord().equals(word)) {
            helpPtr.setNext(helpPtr.getNext().getNext());
         //subtract the frequency of the word to be deleted from the list
            int total = helpPtr.getNext().getFrequency() - countWords;
            break;
        }
        helpPtr = helpPtr.getNext();
    }
}

您的代码实际上是正确的,缺失的部分只是您忘了检查LinkedList的头。

我有一个问题要删除一个节点,但是当我打印列表

时它仍然存在

我不确定为什么您不能删除节点。检查值,因为它们的情况可能有所不同(一个是较低的情况,另一个是上层案例)。但是,如果您不在乎案例,请更改您的插入方法,然后将所有插入单词转换为较低/上的情况。

我只是对您的代码进行了一些调整。请参阅下面:

    public void REMOVEWORD(String word) {
        // declare and initialize a help pointer
        Word helpPtr = head;
        // ADD THIS PART (START)
        if (helpPtr.getWord().equals(word)) { // check if the head is the to be removed word
            head = helpPtr.getNext(); // if true then set head to head.getNext()
            return;
        }
        // ADD THIS PART (END)
        while (helpPtr.getNext() != null) { // iterate through the linkedlist
            if (helpPtr.getNext().getWord().equals(word)) { // check if the next node is the word to be removed
                Word next = helpPtr.getNext().getNext(); // if true then get the next node of the next node
                helpPtr.setNext(next); // set the next of the current node to the acquire node above
                // subtract the frequency of the word to be deleted from the list
                // int total = helpPtr.getNext().getFrequency() - countWords; // NOT SURE WHAT
                // THIS CODE WILL DO SO I JUST COMMENTED IT OUT
                break;
            }
            helpPtr = helpPtr.getNext();
        }
    }

最新更新