【问题标题】:How can i remove and clear memory, from sepecific node of a linked list?如何从链表的特定节点中删除和清除内存?
【发布时间】:2018-11-04 08:19:09
【问题描述】:

所以,我有一个包含 47000 个点头的链接列表。每个节点都有年月日。 我想删除不适合 [month initial, month final] 的节点。因此,如果我选择月份首字母为 3,最后一个月为 8,例如,我想删除那些不适合年份和日期的月份。

LISTAPAISES *Filtra_month(LISTAPAISES * head, int month_init, int month_final) {
    LISTAPAISES *aux=NULL, *elim=NULL, *aux2=NULL; 
    aux=head;
    while(aux !=NULL){
       if(aux->country.month>month_final || aux->country.month<month_init){
          elim=aux;
          aux=aux->next;
          free(elim);
       }
       else{
          if(aux2==NULL){
             aux2=aux;
          }
          aux=aux->next;
      }
   }
   return aux2;
}

这似乎没有得到我想要的点头,但不是清除它们,它只是放入随机数。 有什么建议吗? 提前致谢。

【问题讨论】:

    标签: c list linked-list nodes free


    【解决方案1】:

    假设您有一个链接列表A-&gt;B-&gt;C。 当您通过代码释放B 节点时,前一个节点A 仍然指向旧内存位置B,而不是新节点C。随机数(如果不是分段错误)只是以前读取B 的垃圾内存。

    通过使用两个指针auxahead 来修复它。 aux 指针停留在 ahead 一个节点后面,如果 ahead 通过失败约束 free 它,则将 ahead 分配给 ahead-&gt;next,并相应地更新 aux

    LISTAPAISES* ahead = NULL;
    aux = head;
    // Special case if head passes the failing constain
    if(head != NULL && (head->country.month>month_final || head->country.month<month_init)){
        aux = aux->next;
        free(head);
        head = aux;
    }
    if(aux != NULL){
        ahead = aux->next;
    }
    while(ahead != NULL){
        if(ahead->country.month>month_final || ahead->country.month<month_init){
            // Create a tmp pointer to hold the node after 'ahead'
            LISTAPAISES* tmp = ahead->next;
            free(ahead);
            // Reassign the previous pointer to now point to `tmp`
            aux->next = tmp;
            // Update 'ahead' to be 'tmp' for the next iteration
            ahead = tmp;
        }
        else{
            ahead = ahead->next;
            aux = aux->next;
        }
    }
    
    return head;
    

    【讨论】:

    • 这取决于您需要返回的链表中的哪个节点。从您的代码看来,aux2 是列表中ahead 不满足 if 语句的第一个实例。如果是这种情况,您仍然会返回aux2
    • 我想返回“新”列表的第一个节点,所以我可以使用它。我是带有列表的 kynda noob。
    • @JorgeProença 在编辑中,您只需返回 head
    猜你喜欢
    • 2020-02-11
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多