【问题标题】:Deleting LinkedList With Specific Value Only Once仅删除一次具有特定值的 LinkedList
【发布时间】:2018-11-06 00:39:52
【问题描述】:

我正在编写一个程序,并且在其中一个函数中我必须从 LinkedList 中删除一个值

struct node *delete_val(int value, struct node *head) {

struct node *h1 = head;
if (head == NULL) { return NULL;}
if (head->next == NULL) { free(head); return NULL;}
while (h1 != NULL) {
    if (h1->next != NULL && h1->next->data == value){
        h1->next = h1->next->next;
        } else {
    h1 = h1->next;
}
free(h1);
return head;
}
}    

如果通过:

(4,[3,4,5,6,4,4,7]);

函数应该返回:

[3,5,6,4,4,7]

但我的函数出现错误:

错误:您的函数返回的列表无效。 节点0的next字段无效(0xf5400650)。

我基本上是在检查下一个节点是否在其“数据”(head->next->data)中包含匹配值,如果是,我将重新切换当前链表的指针(head->next) 到它之后的那个 (head->next->next) 但我什至无法让它工作。

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    有两个问题。

    1. 更正链接后需要break(因为要删除一次值)
    2. 您释放的成员不正确。

    如果你纠正这两个,我认为应该没问题。

    struct node *delete_val(int value, struct node *head) {
        struct node *h1 = head;
        struct node *tmp =  NULL;
    
        if (head == NULL) { return NULL;}
        if (head->next == NULL) { free(head); return NULL;}
    
        while (h1 != NULL) {
            if (h1->next != NULL && h1->next->data == value){
                tmp = h1->next;
                h1->next = h1->next->next;
                break;            
            } else {
                h1 = h1->next;
            }    
        }
    
        free(tmp);
        return head;
    }
    

    【讨论】:

      【解决方案2】:

      确保链表还不是空的,而不是

      if (head->next == NULL) { free(head); return NULL;}
      

      if(head->next == NULL)
      {
          if(head->data == value)
          {
              free(head);
              return NULL;
          }
          return head;
      }
      

      只有当data 是要删除的值时,才释放第一个节点。

      至此,我们确定链表中至少有2个节点。

      struct node *temp=NULL, *ptr=head;
      while(ptr->next!=NULL)
      {
          if(ptr->next->data==value)
          {
              printf("\nElement to be deleted found.");
              temp=ptr->next;
              ptr->next=ptr->next->next;
              free(temp);
              break;
          }
          ptr=ptr->next;
      }
      printf("\nElement to be deleted not found in the list.");
      return head;
      

      我们向前看下一个节点的data 是否为value。如果是这样,则将要删除的节点之前的节点的next与要删除的节点的next相等,然后将要删除的节点的内存以free()释放。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-08
        • 2022-08-23
        相关资源
        最近更新 更多