Wom*_*bat 0 c++ linked-list nodes
我觉得好像我实际上没有删除节点并释放内存.我想我只是在移动指针,所以当我打印链表时,列表不打印我删除的元素.所以我的问题是我实际上是删除节点还是我只是简单地重新排列指针所以它看起来像我正在删除节点(基本上只是破坏链接但不删除节点)?感谢您的任何帮助.
void SLL::deleteNode(int target){
Node *current = new Node;
Node *previous = new Node;
for (current = front->next, previous = front; current != NULL; current = current->next, previous=previous->next){
if (previous->data == target && previous == front){
front = previous->next;
delete[] previous;
return;
//This if statement deletes the element if its the front
}
else {
if (previous->data == target && previous->next == NULL){
previous = NULL;
delete[] current;
return;
//This if statement deletes the node if it is the back
}
else if (current->data==target)
{
previous->next = current->next;
delete[] current;
return;
//This if statement deletes a node if it is in the middle
}
}
}
delete[] current;
delete[] previous;
}
Run Code Online (Sandbox Code Playgroud)
Node *current = new Node;
Node *previous = new Node;
Run Code Online (Sandbox Code Playgroud)
此代码导致内存泄漏 - 您永远不会删除此内存.您可以在没有内存分配的情况下声明指针:
Node *current = nullptr;
Node *previous = nullptr;
Run Code Online (Sandbox Code Playgroud)
delete将删除指针的内存,以便您实际删除节点.但使用删除[]为Node* 不正确,与分配的内存- ,应该只针对阵列中使用new[].使用不当会导致不确定的行为.因此,要正确删除节点,请使用operator delete删除它们.
使用内存泄漏检测工具来了解程序中是否存在内存泄漏.
删除列表元素的代码:比方说,我们有pHead指向列表的头部(但如果你自己编写这些东西,它会给你更多):
Node* pCur = pHead;
Node* pPrev = pCur;
while (pCur && pCur->data != target) {
pPrev = pCur;
pCur = pCur->next;
}
if (pCur==nullptr) // not found
return NOT_FOUND;
if (pCur == pHead) { // first element matches
pHead = pCur->next;
} else {
pPrev->next = pCur->next;
}
// pCur now is excluded from the list
delete pCur; // deallocate its memory
Run Code Online (Sandbox Code Playgroud)
使用指针到指针的替代方法(社区添加)
当你实际使用的指针上面可以采取新的光在列表中进行枚举.以下开始pp分配头指针的地址(不是它指向的节点;实际的指针本身).我们遍历列表,直到pp保持指向具有要删除目标的节点的指针的地址(可能是头指针,可能是next某个节点中的指针,没有区别).被寻址的指针被设置为它自己的节点的next值,然后删除目标节点.
这应该在调试器中观察,看看它是如何工作的,但鉴于实际情况,算法非常简单:
Node **pp = &pHead;
while (*pp && (*pp)->data != target)
pp = &(*pp)->next;
if (*pp)
{
Node *victim = *pp;
*pp = victim->next;
delete victim;
}
Run Code Online (Sandbox Code Playgroud)
这就是全部.并且您可以免费获得头部节点,而无需特殊情况.希望这也有帮助.
| 归档时间: |
|
| 查看次数: |
12174 次 |
| 最近记录: |