为什么最后没有插入节点?

我编译代码后,根本没有输出。
为什么链表末尾没有插入值10?
我认为在 p == NULL 之后,while 循环被退出,j->next 也会是 NULL。因此,临时节点将被插入到链表的末尾。

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
}*first=NULL;

void Create(int array[],int size)
{
    int i;
    struct Node *temp,*last;
    first = (struct Node*)malloc(sizeof(struct Node));
    first->data = array[0];
    first->next = NULL;
    last = first;
    
    for (i = 1 ; i < size ; i++){
        temp = (struct Node*)malloc(sizeof(struct Node));
        temp->data = array[i];
        temp->next = NULL;
        last->next = temp;
        last = temp;
    }
}

void Print(struct Node *p)
{
    while(p != NULL){
        printf("%d ",p->data);
        p = p->next;
    }
}

void InsertingInSortedList(struct Node *p,int value)
{
    struct Node *temp,*j = NULL;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = value ;
    temp->next = NULL;
    if(p == NULL){
        first = temp;
    }
    else
    {
        while(p->data < value && p){
            j = p;
            p = p->next;
        }
        temp->next = j->next;
        j->next = temp;
    }
}

int main (void)
{
    int b[] = {1,3,5,7,8,9};
    int num = 6;
    Create(b,num);

    InsertingInSortedList(first,10);
    Print(first);

    return 0;
}
zhuzhuxiangw 回答:为什么最后没有插入节点?

条件 p->data < value && p 是错误的。您需要在取消引用 p 之前检查 p 是否为 NULL

正确的条件是 p && p->data < value

Google c 短路评估了解更多信息。

本文链接:https://www.f2er.com/30743.html

大家都在问