我正在尝试编写一个函数,从给定的链表中删除所有奇数元素,并返回一个地址

时间:2017-05-10 01:32:03

标签: c function linked-list

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

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;

}

1 个答案:

答案 0 :(得分:0)

这是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;
}