在单链表中插入新节点,运行结果不是预期的怎么改呀?
#include "stdio.h"#include "malloc.h"
typedef struct node
{
int data;
int *next;
};
int sum;
struct node * creat(void)
{
struct node *p1,*p2,*head;
p2=p1=head=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p1->data);
head=p1;
while(p1->data!=NULL)
{
p1=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p1->data);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}
struct node * print(struct node *head)
{
struct node *p;
sum=0;
p=head;
while(p->next!=NULL)
{
printf("%d ",p->data);
p=p->next;sum++;
}
}
struct node * insert(struct node *head,struct node * p)
{
struct node *p0,*p1,*p2;
p1=head;
p0=p;
if(head==NULL)
{head=p0;p0->next=NULL;}
else
{
while((p0->data>p1->data)&&(p1->next!=NULL))
{p2=p1;p1=p1->next;}
if(p0->data<=p1->data)
{
if(head==p1)head=p0;
else p2->next=p0;
p0->next=p1;
}
if(p1->next=NULL)
{
p1->next=p0;p0->next=NULL;
}
++sum;
return(head);
}
}
main()
{
struct node *head,*p;
printf("please enter the data of list:\n");
head=creat();
printf("the data of the list are:\n");
print(head);
printf("please enter the data you want to insert:\n");
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
head=insert(head,p);
printf("the new list is:\n");
print(head);
}