【问题标题】:C++ linked lists deleting nodesC++链表删除节点
【发布时间】:2015-11-29 00:17:47
【问题描述】:

我试图通过一个单链表并删除所有包含某个字符的节点。我一直在尝试通过在线查找并尝试这些建议来修复指针错误(它说 glibc 检测到:双重释放或损坏),但现在我似乎在重写我的原始代码后陷入了循环。我认为我至少被困在第三个 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;
}

提前感谢您的帮助。

【问题讨论】:

  • 这段代码错误太多。解决方案应该比这简单得多。您应该尝试完全重新开始,看看会发生什么;尽可能简单。

标签: c++ singly-linked-list


【解决方案1】:

难怪你遇到这样的麻烦。您只需要一个 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;
}

【讨论】:

  • 感谢您的宝贵时间!你的代码很有意义,当我测试它时,虽然我仍然得到 glidbc 检测到的错误。我认为这是因为当我打印出列表时有一个“!”被打印出来。这也发生在我之前。我不确定这是否意味着最后一个指针指向错误。
  • @puredreams7 我不得不假设 first 是列表 head 和全局(例如是 not this),否则代码我给的行不通。如果 glibc 说“双重释放/损坏”[它们通常一起发生],这与段错误略有不同,尽管两者都可能来自相同类型的错误。如果您可以编辑您的问题并发布更多代码,我可以提供进一步的帮助。
猜你喜欢
  • 2019-05-10
  • 2021-07-25
  • 1970-01-01
  • 2017-10-21
  • 2013-08-30
  • 2016-01-02
  • 2019-05-10
  • 2016-03-02
  • 1970-01-01
相关资源
最近更新 更多