循环单链表:从列表中删除特定节点

时间:2012-12-15 13:20:40

标签: c++ 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;
  }
}

2 个答案:

答案 0 :(得分:0)

您有几处内存泄漏:

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;
}

看看这是否能解决您的问题。更多的代码行很少意味着更好的编程技巧,不要人为地试图增加他们的数量。

答案 1 :(得分:0)

我认为另外一个可能的问题是,除了已经记录完备的所有内存泄漏和样式问题之外,你的代码似乎并没有处理列表中只有一件事的情况。

如果发生这种情况,它将删除该节点,但将firstptrlastptr指向随机存储器。

如果你的size_of_list()函数只是计算列表中的节点,它可能仍然认为剩余非零节点,然后你可能会尝试删除或以其他方式访问另一个节点。