递增的整数序列链表的插入过程中遇到的问题

题目要求

img

问题:为什么当我要插入的是-1时,输出的结果最后-1 变成了0 ?

img

img

img

代码


```c
List Insert( List L, ElementType X ){
    List head,p,q;
    head=(struct Node*)malloc(sizeof(struct Node));//创建头指针
    head->Next=L;
    p=head;
    q=(struct Node*)malloc(sizeof(struct Node));;//创建插入结点
    q->Data=X;
    //printf("%d\n",p->Data);
    if(X<=p->Next->Data){
        q->Next=p->Next;
            p->Next=q;
            p=p->Next;
        return head->Next;
    }
    while(p->Next!=NULL){
        if(X<=(p->Next->Data)&&X>p->Data){
            q->Next=p->Next;
            p->Next=q;
            return head->Next;
        };
        p=p->Next;
    }  
        q->Next=NULL;
        p->Next=q;
    return head->Next;}


修改如下,供参考:

typedef struct Node* PtrToNode;
struct Node{
    int  Data;
    PtrToNode Next;
};
typedef PtrToNode List;

List Insert( List L, ElementType  X )
{
    List head,p,q;
    p = L;
    //head=(struct Node*)malloc(sizeof(struct Node));//创建头指针 //修改
    //head->Next=L;
    //p=head;
    q = (struct Node*)malloc(sizeof(struct Node));;//创建插入结点
    q->Data = X;
    q->Next=NULL;
    //printf("%d\n",p->Data); //修改
    //if(X<=p->Next->Data){
    //    q->Next=p->Next;
    //        p->Next=q;
    //        p=p->Next;
    //    return head->Next;
    //}
    while(p->Next!=NULL && p->Next->Data < X){ //修改

        p=p->Next;
    }
    q->Next = p->Next;  //修改
    p->Next = q;        //修改
    return L;   //return head->Next;//修改
}