删除双向链表的最后一个节点(C++)

delete last node of doubly linked list (c++)

我一直在为涉及双向链表的学校项目工作,但我一直无法删除列表的最后一个节点。

bool DLL::remove(string ss, int & count){

    Node* temp = new Node;                              

    if(headPtr == NULL){                                
        return false;                                   
    }
    else{                                               
        temp = headPtr;                                 
        for(int i = 0; i < itemCount-1; i++){           

            if(temp->ssn.compare(ss) == 0){             

                if(temp->pred == NULL){                 
                    count += 1;                         
                    itemCount -= 1;                     
                    headPtr = temp->succ;               
                    return true;
                }
                if(temp->succ != NULL){                 
                    temp->succ->pred = temp->pred;      
                    temp->pred->succ = temp->succ;      
                    return true;
        }
        if(temp->succ == NULL){     
            temp->pred->succ = NULL;
            return true;
        }

    }
    else{
        if(temp->succ == NULL){                 
            return false;                       
        }
        temp = temp->succ;  
    }
        }
    }
    return false;
}

我的代码可以工作,当项目,或者好吧,我现在想到的节点,在开头或中间的任何地方,但当它是列表中的最后一个项目时,它不会删除它。

示例输出:

列表:10、20、30、40、50 当我删除 10、30 和 50 时,结果是 列表:20、40、50

如有任何帮助,我们将不胜感激。 根据我的教授,succ 代表继任者,pred 代表前任。

您迭代到 itemcount - 2 而不是 itemcount - 1,因此忽略了最后一个元素,因为您正在使用 < itemcount - 1。循环应该是:

for (int i = 0; i < itemCount; i++) {
} 

虽然通过以下指针遍历链表要容易得多:

Node *node;
for (node = head; node != NULL; node = node->succ) {
}

除了你的问题,没有必要用 new 分配 temp 因为它是通过分配给 head 等来赋值的。你还应该调用 delete 在您删除的节点上,否则会泄漏内存。