Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 分离链表中的奇数和偶数,分段错误_C - Fatal编程技术网

C 分离链表中的奇数和偶数,分段错误

C 分离链表中的奇数和偶数,分段错误,c,C,将所有奇数项移到链接列表的后面。 利息的作用将是无效的 我很困惑,因为当我使用上面给出的例子时,2,3,4,7,15,18。我能够得到期望的输出 然而,使用例如1,3,4,7,15,18的例子,其中第一个数字是奇数,我在这一行得到了一个分段错误 If the linked list is 2 3 4 7 15 18: The resulting Linked List after moving odd integers to the back of the Linked List is

将所有奇数项移到链接列表的后面。 利息的作用将是无效的

我很困惑,因为当我使用上面给出的例子时,2,3,4,7,15,18。我能够得到期望的输出

然而,使用例如1,3,4,7,15,18的例子,其中第一个数字是奇数,我在这一行得到了一个分段错误

If the linked list is 2  3  4  7  15  18:
The resulting Linked List after moving odd integers to the back of the Linked List is: 2 4 18 3 7 15

我做错什么了吗?

您需要对cur==ll->head的情况进行特殊处理,因为在这种情况下,prev不是合法的先前元素。此外,您还必须更新ll->head


您需要对cur==ll->headValidate所有用户输入的情况进行特殊处理。这意味着至少要验证scanf%d中发生的int转换,&i;通过检查返回值是否为1。如果用户滑倒并输入“q”而不是“1”,会发生什么情况?提示:不好的事情……我不太清楚为什么我需要cur==ll->head的特殊情况,因为对于我的代码,我实际上在while循环之前做了pre=cur,我认为这会“修复”这个特殊情况,在这种情况下pre is!=零对吗?对于第一个元素,您的prev与cur相同。那么你认为当cur移动到最后时会发生什么呢?啊。。如果我把第一行改成pre=cur->next,怎么样?而不是pre->next=cur->next,这有意义吗?编辑:好吧,我知道你就是这么做的。非常感谢我一整天都在忙这个
If the linked list is 2  3  4  7  15  18:
The resulting Linked List after moving odd integers to the back of the Linked List is: 2 4 18 3 7 15
while (cur != tail){
        if(cur->item % 2 != 0) { // <- Segmentation Fault!
            pre->next = cur->next ;
            newTail->next = cur ;
            newTail->next->next = NULL ;
            cur = pre->next ;
            newTail = newTail->next ;
        }
    if(cur->item % 2 != 0) { // <- Segmentation Fault!
    {
        if (cur == ll->head)
        {
            // Add new code here - perhaps something like
            ll->head = cur->next;
            prev = cur->next;
            newTail->next = cur ;
            newTail->next->next = NULL ;
            cur = ll->head;
        }
        else
        {
            // Your current code
        }