C++ 从链表中删除项目时出现问题



上一个问题已解决!

新问题:代码本身。我一直在研究一个函数的代码,用于从链表中删除选定的项目,它可能出现多少次。但是,当我运行程序的该部分以尝试删除节点时,它只会结束程序。我知道有些事情肯定会关闭,但即使看这方面的教程,我也不太了解如何实现这个指令。任何帮助将不胜感激。[已解决]

功能

void LinkedList::deleteItem(int _newItem)
{
if(isEmptyList())
cout << "t<ERROR> List is empty.n";
else
{
bool itemDelete = false;
nodeType *q = first;
while(q != NULL)
{
if(first->info == _newItem)
{
nodeType *p = first->link;
first->link = p->link;
delete p;
--count;
itemDelete = true;
}
if(q->link->info == _newItem)
{
nodeType *r = q;
nodeType *p = q;
r = r->link;
p->link = r->link;
delete r;
--count;
itemDelete = true;
}
q = q->link;
}
if(itemDelete == true)
cout << "Item was deleted.";
else
cout << "Item was not found.";
}

}

类和结构

struct nodeType
{
int info;
nodeType *link;
};
class LinkedList
{
public:
void initializeList();
bool isEmptyList();
void printList();
int findLength();
void destroyList();
int infoFirst();
int infoLast();
bool searchItem(int);
void insertFront(int);
void insertBack(int);
void deleteItem(int);
int calcTotal();
int calcAvg();
LinkedList();
private:
nodeType *first, *last, *newNode;
int count; //adds or remove one whenever a node is added or removed
};

代码的一个问题是这一行:

if(q->link->info == _newItem)

您正在访问链表中的下一个链接,但下一个链接可能是 nullPTR:

if(q->link != nullptr && q->link->info == _newItem)

在访问其成员信息之前,您应该首先检查它是否为 nullptr。

您还应该考虑移动:

if(first->info == _newItem)
{
nodeType *p = first->link;
first->link = p->link;
delete p;
--count;
itemDelete = true;
}

在循环之外,因为如果您尝试删除的节点不是第一个节点,则每次进入循环时都会进行此检查,因为您首先检查的是节点,而不是用于循环链表的节点 q。

另外,请考虑使用 nullptr 而不是 NULL。

else
{
bool itemDelete = false;
nodeType *q = first;
if(first->info == _newItem)
{
nodeType *p = first->link;
first->link = p->link;
delete p;
--count;
itemDelete = true;
}
// by doing !itemDelete you will exit once you find the item
// or you won't enter the loop if the item was the first in the list
while(q != nullptr && !itemDelete)
{
if(q->link != nullptr && q->link->info == _newItem)
{
nodeType *r = q;
nodeType *p = q;
r = r->link;
p->link = r->link;
delete r;
--count;
itemDelete = true;
}
q = q->link;
}
if(itemDelete == true)
cout << "Item was deleted.";
else
cout << "Item was not found.";
}

此处的此部分可以进一步折叠:

// by doing !itemDelete you will exit once you find the item
while(q != nullptr && !itemDelete)
{
if(q->link != nullptr && q->link->info == _newItem)
{
nodeType *r = q;
nodeType *p = q;
r = r->link;
p->link = r->link;
delete r;
--count;
itemDelete = true;
}
q = q->link;
}

自:

// by doing !itemDelete you will exit once you find the item
while(q->link != nullptr && !itemDelete)
{
if(q->link->info == _newItem)
{
nodeType *r = q;
nodeType *p = q;
r = r->link;
p->link = r->link;
delete r;
--count;
itemDelete = true;
}
q = q->link;
}

我希望这对您有所帮助。

相关内容

  • 没有找到相关文章

最新更新