【问题标题】:Removing some elements from a linked list in C从C中的链表中删除一些元素
【发布时间】:2015-07-06 16:13:34
【问题描述】:

我必须从链表中删除所有小于或等于“媒体”的元素。我已经编写了这个函数,但它在某些输入上不起作用。

代码:

typedef struct lista {
        int dato;
        struct lista *next;
        }
    node;

......
.....
.....

void filtra_elementi(node ** head, int media)
{
node *prec, *corr;
while(((*head)->dato <= media) &&((*head!=NULL)))
    {
    corr=(*head)->next;
    free(*head);
    *head=corr;

    }
prec=*head; corr=(*head)->next;
while(corr!=NULL)
    {
    if(corr->dato<=media)
      {
      prec->next=corr->next;
      //free(corr);
      corr=prec->next;
      }
     else prec=corr; corr=corr->next;
    }
}

这里是函数。 如果列表是,它不起作用 0 10 1 11 3 13 4 14 5 15 有人可以向我解释为什么吗?谢谢。

【问题讨论】:

  • 你为什么不把你的代码放在这里。
  • 请具体说明,它不起作用是什么意思,即期望什么以及实际输出/结果是什么
  • 你是对的,但我不知道该怎么做。目标是删除不等于“媒体”(参数之一)的元素。但是如果我将输入 0 10 1 11 3 13 4 14 5 15 作为原始列表提交,那么第二个就会出现问题
  • 是的,但是 what “某事”?
  • while(((*head)-&gt;dato &lt;= media) &amp;&amp;((*head!=NULL))) { 更改顺序。 (短路保证订单)

标签: c list average


【解决方案1】:
 corr=prec->next;
  }
 else prec=corr; corr=corr->next;//corr=corr->next is not in else part and will always be executed.
}

你想要的是

 corr=prec->next;
  }
 else 
 {prec=corr; 
  corr=corr->next;
 }
}

你的while条件也是错误的。你应该改变检查的顺序。想想如果(*head)null会发生什么然后访问(*head)-&gt;dato)会导致运行时错误。如果你使用这个

while(((*head!=NULL)) && ((*head)->dato <= media))

如果 (*head)null (*head)-&gt;dato 将不会被访问。

【讨论】:

  • corr=corr->下一个;不是 else 的一部分。没有括号 { },否则只会使用下一个语句。这是具有误导性的,因为您在视觉上将它们放在同一条线上。
  • @GiovanniMauro corr=corr-&gt;next 无论if部分被执行还是else部分被执行都将被执行。因为它不在else部分,它是一个单独的语句,将在每次运行 while 循环
  • 我是个笨蛋,我不知道为什么我忘记了else后面的括号。非常非常感谢大家!
【解决方案2】:

这是另一个版本的函数,稍微简单一点,只有一个循环

void filtra_elementi(node **head, int media)
{
 node *next;
 while(*head != NULL) {
    next = (*head)->next;
    if((*head)->dato <= media) {
        free(*head);
        *head = next;
    } else {
        head = &((*head)->next);
    }
 }
}

【讨论】:

  • "Next" 是结构体的一个字段
猜你喜欢
  • 2014-10-25
  • 2020-09-04
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2020-10-29
相关资源
最近更新 更多