循环单链表:从列表中删除特定节点
Circular Singly Linked List: Remove a particular Node from List
我编写了代码以根据用户从列表中删除特定节点选择,代码对于特定值完全有效,但如果我使多次调用它,这意味着如果我连续调用它 2 次,那么我的一个另一个函数pointer_to_node(index)
给出一个越界错误,也是我为了记录这样的条件而实施的,
实际上,我需要多次调用的原因是我必须编写一个单独的函数以删除所有节点。我正在尝试使用此来完成该任务函数通过使用最大为我的循环单链表大小的for
循环。但在这种情况下,它还会返回我一个NULL
指针并让我出界消息(由我在代码中实现)。我已经包含了我的两个功能这里
void remove_from_index(int index){
Node*temptr;
temptr = new Node;
int tempdata;
if (index==1)//means remove from first
{
temptr = firstptr;
tempdata= temptr->data;
firstptr = firstptr->nextptr;
lastptr->nextptr=firstptr;
delete(temptr);
} else if(index==size_of_list()) //means last node
{
temptr = pointer_to_node(index);
index--; //get pointer of 2nd last position
lastptr = pointer_to_node(index);//setting 2nd last as last postion
temptr->nextptr=NULL;
temptr=NULL;
lastptr->nextptr=firstptr;
delete (temptr);
} else // any position of node
{
temptr = pointer_to_node(index);
tempdata = temptr->data;
index--; // to get address of back
Node* temp2ptr;
temp2ptr = new Node;
temp2ptr = pointer_to_node(index);
index = index+2;
Node* temp3ptr;
temp3ptr = new Node;
temp3ptr = pointer_to_node(index);
temp2ptr->nextptr = temp3ptr;
temptr->nextptr=NULL;
delete (temptr);
}
}
Node* pointer_to_node(int index){
Node*temptr;
temptr = new Node;
temptr = firstptr;
Node*temptr2;
temptr2 = new Node;
temptr2 = NULL;
int count = 1;
while (temptr!=temptr2){
if (count==index)
{
return temptr;
}
count++;
temptr2=firstptr;
temptr=temptr->nextptr;
}
if (index>size_of_list())
{
temptr=NULL;
cout<< "Can't You think in bounds. Take your NULL Pointer ";
return temptr;
delete temptr;
delete temptr2;
}
}
您有几个内存泄漏:
temptr->nextptr=NULL;
temptr=NULL; // BAD!! BAD!! Remove it otherwise you will not actually free
lastptr->nextptr=firstptr;
delete (temptr);
这里也是(实际上你在代码的四个地方都有这个):
Node* temp2ptr;
temp2ptr = new Node; // BADD!! Why do you allocate if you are going to reassign?
temp2ptr = pointer_to_node(index);
删除坏处,您将避免内存泄漏。
不过,这并不能解决您的问题。
返回后您也有操作:
return temptr;
delete temptr;
delete temptr2;
这些永远不会被执行。
编辑 您的pointer_to_node
功能太复杂,请将其更改为
Node* pointer_to_node(int index) {
Node* tempPtr = firstptr;
for (int i = 0; i < index; i++) {
tempPtr = tempPtr->nextptr;
}
return tempPtr;
}
看看这是否会解决您的问题。更多的代码行很少意味着更好的编程技能,不要人为地试图增加它们的数量。
我认为除了所有已经有据可查的内存泄漏和样式问题之外,这里的另一个可能问题是您的代码似乎无法处理列表中只有一件事的情况。
如果发生这种情况,它将删除该节点,但保留指向随机内存的firstptr
和lastptr
。
如果您的 size_of_list() 函数只是计算列表中的节点,它可能仍然会认为剩余的非零节点,然后您可能会尝试删除或以其他方式访问另一个节点。
相关文章:
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 删除列表 c++ 中的最后 3 个元素
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- C++ 从具有开始位置和结束位置的列表中删除
- 从列表向量中删除无法按预期工作
- 从列表C++中删除对象
- 简单的链接列表删除失败
- C++循环链接列表 - 删除所有节点
- 链接列表删除节点C
- 链接列表删除
- 矢量与来自 STL 的列表 - 删除方法
- 运算符== 和列表::删除()