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

一个新的链表中的奇数元素被移除。 我发现这项任务非常复杂,如果您能帮助修复或改进我的代码,我会很高兴。 到目前为止,这是我所做的:

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)
{
       LNode* newNode = createNewNode(newData, NULL);

    list->next= newNode;

}

【问题讨论】:

  • 为什么在 args 中使用 List** 而不是 List* ?
  • ... removeOddValues(List** source) { List* curr= source; 应该引发编译器警告。节省时间,启用所有编译器警告。

标签: c function linked-list


【解决方案1】:

这是 removeOddValues 函数的编辑版本(未经测试)。你没有说返回值应该是什么,所以我只是猜测它应该是列表的新头部。您将需要实现一个函数removeFromList 来取消链接元素,但是有很多可用的示例(例如:I am having issues with pointer use in C)。

希望对您有所帮助。

List* removeOddValues(List** source)
{
    List * resultHead = NULL;

    List * currentElem = *source;
    List * nextElem    = NULL;

    while (currentElem)
    {
        // remove invalid elements (those with odd value)
        if (currentElem->data % 2 == 1)
        {
            removeFromList(currentElem);
        }
        // use the first valid element as new head of the list
        else
        {
            resultHead = resultHead ? resultHead : currentElem;    
        }

        currentElem = nextElem;
    }

    // return new head of the list
    // will be NULL if all elements were odd
    return resultHead;
}

【讨论】:

  • if (currentElem->data % 2 == 1) 适用于正奇数,但不适用于负奇数。 OP 的 if ((curr->data)%2!=0) 在功能上是正确的。
  • removeFromList(currentElem); 肯定是不正确的,因为该函数调用的效果不会更改removeOddValues() 中的任何变量。 nextElem 仅设置为 NULL 并且从未更改。建议重写代码。
  • @volzo,它对我没有多大帮助...我想使用函数 List* createNewNode(int newData, List* next) 和 void insertNodeToEnd(List** list, type newData)
  • 对不起,Gal,您的问题中没有指定... @chux 你错了。如果您不知道链表是​​如何工作的(请参阅 stackoverflow 上的许多帖子),您可以看到通过调整指针(指向下一个/上一个)删除了一个元素。所以,这将通过调整相邻元素的指针来工作,这肯定会在函数removeOddValues之外。
  • ... @chux 是对的,因为 List * nextElem = NULL; 是多余的。没有那条线,它应该是一个好的、紧凑的解决方案。如果需要,您当然可以考虑使用其他实用功能。
猜你喜欢
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
相关资源
最近更新 更多