c - 如何将链表拆分为2个列表?

标签 c list split

在我的代码中,有 2 个列表。我想将它们分开:偶数和奇数。
我写了一些东西。但是,它没有打印出我想要的内容。我要做什么?

if((list->data) % 2 == 1){
    oddList = list;
    list = list->nextPtr;
    oddList->nextPtr = NULL;
    printList(oddList);
} else {
    evenList = list;
    list = list->nextPtr;
    evenList->nextPtr = NULL;
}
list = list->nextPtr;    

结果是:

list1 : 4 17 17 19 21 28 31 
list2 : 5 5 10 14 19 31 34 35 
oddList : 5 17 19 31 31 
evenlist :

但是oddList必须是:5 5 17 17 19 19 21 31 31 35

最佳答案

您正在推进 list 两次

    if ((list->data) % 2 == 1) {
        oddList = list;
        list = list->nextPtr;            // first advance
        oddList->nextPtr = NULL;
        printList(oddList);
    } else {
        evenList = list;
        list = list->nextPtr;            // first advance
        evenList->nextPtr = NULL;
    }
    list = list->nextPtr;                // second advance
} 

关于c - 如何将链表拆分为2个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733159/

相关文章:

python - Python 中的 "Slice lists"和 "the ellipsis";切片列表和带有切片列表的列表列表

r - 如何在 R 中使用 strsplit 制作字符串向量?

c# - 如何从字符串中获取第一组字母字符?

c - 为什么这段代码不能继续?

c# - 按月将一个列表拆分为多个 - C#、Linq

python - 从 Python 中的元组列表中迭代查找/替换

python - 如何拆分从文件中读取的字符串

c - 多线程 printf() 与 c 中的信号量

c - 如何在 QNX Momentics 6.5 中使用不同的编译标准?

C指针不在同一个地址