想用链表写,链表初始元素五个以上就老是输出不全,求解

想用链表写,链表初始元素五个以上就老是输出不全,求解

问题描述:

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

typedef struct node
{
int data;
struct node* Pnext;
}NODE,*PNODE;

PNODE creat();
void sort_insert();
void traverse();

int main(int argc, char** argv)
{
PNODE p = NULL;
p = creat();
sort_insert(p);
traverse(p);
return 0;
}

PNODE creat(void)
{
int len;
int i;
int val;
PNODE Phead = (PNODE)malloc(sizeof(NODE));
if (Phead==NULL)
{
printf("头节点分配失败");
exit(-1);
}
PNODE Ptail = Phead;
Ptail->Pnext = NULL;
scanf("%d",&len);
for (i=0;i<len;++i)
{
PNODE Pnew = (PNODE)malloc(sizeof(NODE));
if (Pnew==NULL)
{
printf("新节点分配失败");
exit(-1);
}
scanf("%d",&val);
Pnew->data = val;
Ptail->Pnext = Pnew;
Ptail = Pnew;
Ptail->Pnext = NULL;
}
return Phead;
}

void traverse (PNODE p)
{
//PNODE pp = p->Pnext;
while(p->Pnext!=NULL)
{
p = p->Pnext;
printf("%d ",p->data);
}
return;
}

void sort_insert(PNODE p)
{
int val;
int i;
scanf("%d",&val);
while(p->Pnext->data < val)
{
p = p->Pnext;
}
PNODE Pnew = (PNODE)malloc(sizeof(NODE));
if (Pnew==NULL)
{
printf("新节点分配失败");
exit(-1);
}
Pnew->data = val;
PNODE tp;

  p->Pnext = tp;
  p->Pnext = Pnew;
  Pnew->Pnext = tp;
  return;

}

  • ```

![img](https://img-mid.****img.cn/release/static/image/mid/ask/667717267736136.jpg "#left")

sort_insert函数有问题,代码修改如下:

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

typedef struct node
{
    int data;
    struct node* Pnext;
}NODE,*PNODE;

PNODE creat();
void sort_insert(PNODE p);
void traverse(PNODE p);

int main(int argc, char** argv)
{
    PNODE p = NULL;
    p = creat();
    sort_insert(p);
    traverse(p);
    return 0;
}

PNODE creat(void)
{
    int len;
    int i;
    int val;
    PNODE Phead = (PNODE)malloc(sizeof(NODE));
    if (Phead==NULL)
    {
        printf("头节点分配失败");
        exit(-1);
    }
    PNODE Ptail = Phead;
    Ptail->Pnext = NULL;
    scanf("%d",&len);
    for (i=0;i<len;++i)
    {
        PNODE Pnew = (PNODE)malloc(sizeof(NODE));
        if (Pnew==NULL)
        {
            printf("新节点分配失败");
            exit(-1);
        }
        scanf("%d",&val);
        Pnew->data = val;
        Ptail->Pnext = Pnew;
        Ptail = Pnew;
        Ptail->Pnext = NULL;
    }
    return Phead;
}

void traverse (PNODE p)
{
    //PNODE pp = p->Pnext;
    while(p->Pnext!=NULL)
    {
        p = p->Pnext;
        printf("%d ",p->data);
    }
    return;
}

void sort_insert(PNODE p)
{
    int val;
    int i;
    PNODE pre = p;
    PNODE q = pre->Pnext;
    scanf("%d",&val);

    while(q && q->data < val)
    {
        pre = q;
        q = q->Pnext;
    }
    PNODE Pnew = (PNODE)malloc(sizeof(NODE));
    if (Pnew==NULL)
    {
        printf("新节点分配失败");
        exit(-1);
    }
    Pnew->data = val;
    pre->Pnext = Pnew;
    Pnew->Pnext = q;
    /*PNODE tp;

    p->Pnext = tp;
    p->Pnext = Pnew;
    Pnew->Pnext = tp;*/
    return;
}

while(p->Pnext->data < val)
{
p = p->Pnext;
}
这个循环有问题啊。p->Pnext总会等于NULL的啊