c链表删除函数

标签 c linked-list

<分区>

大家好,我必须用 C 语言编写一个程序,但我无法创建函数 deleteByPrice - 用于删除所有价格高于我必​​须在控制台中输入的价格的结构的函数 这是我的结构

 typedef struct  
    {
       char name[20];
       char id[20];
       float price;
    }Type;

typedef struct Details {
    Type data;
    struct Details *next;
}Node;

这就是我编写的代码但不起作用:

Node *deleteByPrice(Node *start) {
    Node *cur =start;
    Node *next=start;
    float price;
    printf("Insert the price here : ");
    scanf("%f",&price);
    while(cur){
      if (price < cur->data.price){
            next=cur->next;
            free(cur);
            cur = next;
            start=cur;
            } 
       else {           
            next = cur->next->next;
            free(cur->next);
            cur->next = next;
            }
       }
   return cur;
 }

最佳答案

好吧,while 循环中的两个分支都不正确。首先,当价格低于控制台上给出的价格时,您应该使用 cur = cur->next 跳转到下一个元素;无需弄乱链接列表中的任何项目。第二,当价格大于给定的价格而您必须删除该项目时,删除必须按如下方式进行:

  1. 您必须将 previous 项目的 next 指针链接到当前项目之后的项目(即 cur->next。由于您只允许在链接中“向前”移动,这意味着您必须跟踪上一个 项目以及当前项目;使用一个名为 的额外指针prev,从空指针开始,在 cur 步进到下一项之前设置为 cur while 循环。一旦有了 prev,就可以使用 prev->next = cur->next 从列表中删除要删除的项目。(注意这不会释放该项目)。

  2. 从列表中删除要删除的项目后,您可以使用 free(cur) 安全地释放它并移至列表中的下一个项目。但是,由于 cur 现在是 free 之后的无效指针,您必须先将 cur->next 记录在变量 before 释放 cur 然后将 cur 设置为这个记录的值以继续遍历列表。

整个解决方案归结为:

prev = 0; cur = start;
while (cur) {
    if (cur->data.price < price) {
        /* keep the item and move to the next one */
        prev = cur;
        cur = cur->next;
    } else {
         /* remember the item after the item being removed */
         next = cur->next;
         /* unlink the item from the list */
         if (prev) {
             prev->next = next;
         }
         /* free the unlinked item */
         free(cur);
         /* move to the next item */
         cur = next;
         /* note that prev does not have to be modified here */
     }
 }

此外,这里还有一个问题。如果您碰巧从列表中删除第一项,这意味着调用 deleteByPrice 的函数持有的用于访问列表第一项的指针不再有效,因此您必须 当您删除列表的第一项时,相应地更新 start,并且您必须在函数结束时返回 start这样调用者就会知道列表的"new"头在哪里。我故意从上面的代码中省略了这一点——如果您理解我的代码,那么添加起来应该不难。

关于c链表删除函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8502766/

相关文章:

具有指针的结构的 const 正确性

c - 使用 C 中的线程获取用户输入而不阻塞 while 循环

用于 LinkedList 的 Java compareTo

c++ - 如何引用 C++ 中所谓的函数?

c++ - 对 `__imp_WSACleanup' 的 undefined reference

python - 将任意长度的列表或元组传递给用 C 编写的 Python 扩展

c - 无限循环链表 C

c - 在 C 中通过双指针访问结构元素

c - C 中的链表 – 方法

c - 如何将递归函数转换为迭代函数?