【问题标题】:I am trying to write a function that removes all the odd elements from a given linked-list and also returns an adress of我正在尝试编写一个函数,从给定的链表中删除所有奇数元素,并返回一个地址
【发布时间】:2017-05-10 07:58:47
【问题描述】:

我正在尝试编写一个函数,该函数从给定的链表中删除所有奇数元素,并返回一个新链表的地址,该链表包含已删除的奇数元素。我发现这项任务相当复杂,如果您能帮助修复或改进我的代码,我将非常高兴。

这是我到目前为止所做的:

typedef struct list{
      int data;
      struct  list* next;
} List;


List* removeOddValues(List** source)
{
      List* curr= source;
      List* prev;
      List* odd= NULL;

      while (curr)
      {
        if ((curr->data)%2!=0)
          {
           insertNodeToEnd(&odd, curr->data);
           prev->next = curr->next;
          }
        else
          {
           prev = curr;
           curr= curr->next;
          }
      }
     return odd;
}

List* createNewNode(int newData, List*  next)
{
       List* newNode = (List)calloc(1, sizeof(List));
       newNode->data = newData;
       newNode->next = next;

       return newNode;
}

void insertNodeToEnd(List** list, type  newData) //insert a new node to list //
{
       LNode* newNode = createNewNode(newData, NULL);

    list->next= newNode;

}

【问题讨论】:

  • 1) List* curr= source; --> List* curr= *source;... 实际插入/删除处理没有做完。
  • @BLUEPIXY 你能解释一下原因吗?
  • source 的类型是 List **,而不是 List *
  • 我该如何修复我的代码?
  • 您的代码未处于更正级别,因为缺少主要部分。我发布了一个代码示例作为答案。

标签: c list linked-list


【解决方案1】:

像这样:

List* removeOddValues(List **source){
    List *curr = *source;
    List even = { .next = NULL };
    List *e_curr = &even;
    List odd  = { .next = NULL };
    List *o_curr = &odd;

    while(curr){
        List *next = curr->next;
        curr->next = NULL;

        if(curr->data % 2)// != 0, odd
            o_curr = o_curr->next = curr;//node add to last
        else//even
            e_curr = e_curr->next = curr;

        curr = next;
    }
    *source= even.next;//update source
    return odd.next;
}

【讨论】:

  • 对不起,@BLUEPIXY,它对我没有多大帮助...我希望通过使用我编写的函数来改进我的代码...
  • @Gal1988 首先,您需要完成每个较低的功能。 (这显然是不完整的。)要删除的代码,要循环的代码存在缺陷。此外,您需要释放您离开链接的节点。 (我觉得没必要新建节点)
  • 但我不知道如何完成它们...我不太清楚
  • 如何通过新建节点来实现?
  • @Gal1988 我可以展示有关它们的代码,但如果您想使用您的逻辑,我认为您应该先自己编写。实际上,这个网站上有很多将节点插入列表和删除的例子。请自行搜索代码编写。那么如果遇到问题请再次提问。
猜你喜欢
  • 2017-10-08
  • 2017-10-08
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
相关资源
最近更新 更多