从结构中删除项目

时间:2012-03-29 00:06:58

标签: c pointers structure

我有以下链接列表:

struct scoreentry_node {
    struct scoreentry_node *next;
    int score;
    char name[1];    
}
;

typedef struct scoreentry_node *score_entry;

我正在尝试编写一个删除包含特定名称的所有节点的函数。这是我到目前为止,但我不确定我是对的:

score_entry disqualify(score_entry a, char* name)
{
 score_entry tmp = a;
 while (tmp != NULL){
    if (strcmp(tmp->name, name) == 0)
    {
     score_entry trash = tmp; 
     tmp = tmp->next;    
     free(trash);
    }
    else { tmp = tmp->next; }
  }
return a;
}

它给了我堆错误..有什么建议吗?

3 个答案:

答案 0 :(得分:3)

score_entry disqualify(score_entry a, char* name)
{
  score_entry new_front = a, tmp;
  // delete "wrong" entries from the front
  while (new_front != NULL){
    if (strcmp(new_front->name, name) == 0)
    {
      score_entry trash = new_front; 
      new_front = new_front->next;    
      free(trash);
    }
    else
    {
      // first list entry is valid
      // delete "wrong" entries from inside the list
      tmp = new_front;
      while ( tmp->next != NULL )
      {
        if ( strcmp(tmp->next->name,name)==0 )
        {
          score_entry trash = tmp->next;
          tmp->next = tmp->next->next;
          free(trash);
        } else
        {
          tmp = tmp->next;
        }
      }
    }
 }
return new_front;
}

您还应该获得一些与常见数据结构相关的书籍 - 您似乎对这些内容感兴趣,这对您有很大的帮助。

答案 1 :(得分:0)

您在非空终止字符串(strcmp)上使用tmp->name。我假设它不是以空值终止的,因为它只有长度为1.看起来你真的在比较一个字符,而不是一个字符串,所以一个简单的字符相等运算符是正确的。

答案 2 :(得分:0)

如果从列表中删除某个成员,则必须通过将前一个条目的“下一个”指针链接到以下条目来修复此创建的间隙。下面的代码就是这样。请注意,我已更改score_entry,以便typedef不再包含指针 - 我不想伪装类型。请注意,如果我们删除列表中的第一个条目,该函数将返回可能已更改的head

typedef struct scoreentry_node score_entry;

static score_entry *
disqualify(score_entry *head, const char *name)
{
    score_entry *se = head;
    score_entry *prev = head;

    while (se) {
        if (!strcmp(se->name, name)) {
            score_entry *next = se->next;

            if (head == se) {
                head = next;
            } else {
                prev->next = next;
            }
            free(se);
            se = next;

        } else {
            prev = se;
            se = se->next;
        }
    }
    return head;
}
相关问题