[英]Circular Singly Linked List: Remove a particular Node from List
我写了代码,根据用户的选择从列表中删除了一个特定的节点,代码对于一个特定的值工作得很好,但是如果我多次调用它,这意味着如果我连续调用两次,那么我的另一个函数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()函数只是对列表中的节点进行计数,它可能仍会认为还有非零节点,然后您可能会尝试删除或以其他方式访问另一个节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.