C ++链接列表删除节点

时间:2015-11-29 00:17:48

标签: c++ singly-linked-list

我正在尝试浏览单个链接列表并删除包含某个char的所有节点。我一直试图通过在线查找并尝试这些建议来修复指针错误(它说glibc检测到:双重免费或损坏)但现在我似乎在重写原始代码后陷入循环。我认为我至少停留在第3个while循环中,我尝试过使用if和else语句但是同样的事情发生了。我有时也会遇到分段错误。

代码:

int MonsterList::removeMonsterType(char monster){
  if(!isalpha(monster)) return 0;
  if(first == 0) return 0;

  int count = 0;
  char key = toupper(monster);

  MonsterNode *prev = first; //first is the ptr in the list this function is called on
  if(prev->next == 0){
    while(prev->id == key || prev->id == key+32){
      first = 0;
      delete prev; prev = 0;
      count++;
      return count;
    }
    return count;
  }

 MonsterNode *temp = prev->next;

 while(temp != NULL){
   while(prev->id == key || prev->id == key+32){
     first = temp;
     delete prev;
     prev = temp;
     temp = temp->next;
   }
   while(temp->id == key || temp->id == key+32){
     prev->next = temp->next;
     delete temp;
     temp = prev->next;
     count++;
   }
   prev = temp;
   temp = temp->next;
 }

 return count;
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

难怪你遇到这样的麻烦。你只需要一个for循环。请允许我简化您的代码[请原谅一些无偿的样式编辑]。请注意,这是未经测试的,可能并不完美:

int
MonsterList::removeMonsterType(char monster)
{
    if (!isalpha(monster))
        return 0;

    // first is the ptr in the list this function is called on
    if (first == 0)
        return 0;

    int count = 0;
    char key = toupper(monster);

    MonsterNode *prev;
    MonsterNode *cur;
    MonsterNode *next;

    prev = NULL;
    for (cur = first;  cur != NULL;  cur = next) {
        // grab this _first_ so we have it before cur may be deleted (e.g. if
        // cur gets deleted cur->next is immediately invalid, but this will
        // remain)
        next = cur->next;

        if ((cur->id == key) || (cur->id == (key + 32))) {
            // link previous item to next item
            if (prev != NULL)
                prev->next = next;

            // replace first item in list
            else
                first = next;

            // delete the node and advance the count
            delete cur
            count++;

            continue;
        }

        // remember previous item
        prev = cur;
    }

    return count;
}