传递值时,我需要删除甜点节点。我搜索链表,出现匹配,删除节点并返回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位置。
答案 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;
}