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

标签 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;

}

最佳答案

像这样:

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

关于c - 我正在尝试编写一个函数,从给定的链表中删除所有奇数元素,并返回一个地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43886651/

相关文章:

c - C 中的下标函数

r - 将不对称向量列表转换为矩阵

list - 如何打印返回列表的 Perl 表达式的第 n 个元素?

c++ - 链表增加节点数

Java 线程无法与链表正常工作

C 客户端只能连接到 localhost。

c - Visual Studio 2010 中的 C 程序调试失败

Java排序双链表: How to insert a new node quickly in the right position?

c - 正确解析 C 中的命令行参数

python - 创建相互独立的 Python 变量