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

时间:2017-05-10 07:58:47

标签: c list 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) //insert a new node to list //
{
       LNode* newNode = createNewNode(newData, NULL);

    list->next= newNode;

}

1 个答案:

答案 0 :(得分:0)

像这样:

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