这个链表的代码不知道为什么不行

这个代码不知道为什么不行
#include<stdio.h>

#include<stdlib.h>
struct node
{
int x;
struct node *next;
}
main(){
struct node *h,*p1,*p2;
int i,n,a[10];
printf("请输入链表的长度:");
scanf("%d",&n);
printf("请输入链表的所有元素:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
p1=(struct node*)malloc(sizeof(struct node));
p1->x=a[i];
if(h=NULL)
h=p2=p1;
else if(p1->x%2==1)
{
p1->next=h;
h=p1;
}
else
p2->next=p1;
}
printf("构建完成");
p2->next=NULL;
p1=h;
for(i=0;i<n;i++)
{
printf("%d",p1->x);
p1=p1->next;
}
}

运行后,输入完就不行了

1、struct node *h,*p1,*p2;是初始化结构体的指针h p1 p2,此时h p1 p2均不为NULL,但由于未申请分配内存,所以都是野指针
2、h=NULL是将NULL赋值给h,并不是判断h是否是NULL,所以if(h=NULL)的判断条件就会一直是假的,就算是if(h==NULL)判断的h是否是NULL这条件也会一直是假的,因为h已经初始化并没有赋值为NULL,其就不会是NULL
3、看你这逻辑应该是要将奇数排在前边,偶数排在后边,但是为偶数的时候只做了p2->next=p1;还缺少将p2往后移一位p2 = p1;
修改后的代码参考如下:

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int x;
    struct node *next;
};
int main(int argc, const char * argv[]) {
    struct node *h,*p1,*p2;
    int i,n,a[10];
    printf("请输入链表的长度:");
    scanf("%d",&n);
    printf("请输入链表的所有元素:");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    for(i=0;i<n;i++) {
        p1=(struct node*)malloc(sizeof(struct node));
        p1->x=a[i];
        if(i == 0){
            h=p1;
            p2=p1;
        } else if(p1->x%2 == 1){
            p1->next=h;
            h=p1;
        } else {
            p2->next=p1;
            p2 = p1;
        }
    }
    printf("构建完成");
    p2->next=NULL;
    p1=h;
    for(i=0;i<n;i++) {
        printf("%d",p1->x);
        p1=p1->next;
    }
    return 0;
}

供参考:

#include <stdio.h>
#include <stdlib.h>
struct node{
    int x;
    struct node* next;
};
int main() 
{
    struct node* h = NULL, * p1 = NULL, * p2 = NULL;  //修改
    int i, n, a[10];
    printf("请输入链表的长度:");
    scanf("%d", &n);
    printf("请输入链表的所有元素:");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for (i = 0; i < n; i++)
    {
        p1 = (struct node*)malloc(sizeof(struct node));
        p1->x = a[i];
        if (h == NULL)     //if (h = NULL) 修改
            h = p2 = p1;
        else if (p1->x % 2 == 1)
        {
            p1->next = h;
            h = p1;
        }
        else {
            p2->next = p1;
            p2 = p1;     //修改
        }
    }
    printf("构建完成");
    p2->next = NULL;
    p1 = h;
    for (i = 0; i < n; i++)
    {
        printf("%d", p1->x);
        p1 = p1->next;
    }
    return 0;
}