C ++特定节点链接列表删除。代码有意义吗?

时间:2016-08-26 06:10:40

标签: c++ linked-list

传递值时,我需要删除甜点节点。我搜索链表,出现匹配,删除节点并返回true。如果未找到值,则返回false。

bool LinkedList::delNode(string flavor)
{
    Dessert *pointer1 = head;
    Dessert *ptrT;
    while (pointer1 != NULL) {
        if (pointer1->flavor != flavor) {
            ptrT = pointer1;
            pointer1 = pointer1->next;
        } else { 
            ptrT->next = pointer1->next;
            delete pointer1;
            return true; 
        // Should I add a break here ?
        } 
        else if(pointer1->next == NULL) { return false; } 
    }
}

我不完全确定这里的编码是否适用于所有可能的Node位置。

3 个答案:

答案 0 :(得分:0)

从函数return开始,不会再执行任何语句,因此在break之后添加return不会产生任何影响。

答案 1 :(得分:0)

保持if/ else if/ else正确的顺序。这里,lase else if语句没有if语句。您可能会收到错误

  

错误:'else'没有先前的'if'

 if (pointer1->flavor != flavor) {
     ptrT = pointer1;
     pointer1 = pointer1->next;
 } 
 else if (pointer1->next == NULL) { return false; } 
 else { 
    ptrT->next = pointer1->next;
    delete pointer1;
    return true; 
 } 

答案 2 :(得分:0)

你应该初始化ptrT指针,如果你的代码遇到else情况(只考虑删除head节点,那么程序就会崩溃。

bool LinkedList::delNode(string flavor)
{
    Dessert *pointer1 = head;
    Dessert *ptrT = NULL;
    while (pointer1 != NULL) {
        if (pointer1->flavor != flavor) {
            ptrT = pointer1;
            pointer1 = pointer1->next;
        }
        else if(pointer1->next == NULL) {
            return false;
        }
        else {
            if (ptrT == NULL) {
                head = pointer1->next;
            }
            else {
                ptrT->next = pointer1->next;
            }
            delete pointer1;
            return true;
        }
    }
    return false;
}