结点的插入
#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(struct student)
struct student
{
long num;
int score;
struct student *next;
};
struct student *create(int n)
{
struct student *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct student *)malloc(LEN);
scanf("%ld",&p1->num);
scanf("%d",&p1->score);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%8ld%8d",p->num,p->score);
p=p->next;
printf("\n");
}
}
struct student *insert(struct student *head, struct student *stud)
{
struct student *p0,*p1,*p2;
p1=head;//头指针
p0=stud;//第二个指针
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while((p0->num>p1->num)&&(p1->next!=NULL))//比较学号的大小
{
p2=p1;
p1=p1->next;
}
if(p0->num<p1->num)
{
if(head==p1)
{
head=p0;
}
else
p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
}
}
return head;
}
int main()
{
struct student *head,*stu;
int n;
scanf("%d",&n);
head=create(n);
print(head);
stu=(struct student *)malloc(LEN);
scanf("%ld",&stu->num);
scanf("%d",&stu->score);
stu->next = NULL;
head=insert(head,stu);
print(head);
return 0;
}
/*struct student *insert(struct student *head, struct student *stud)
{ struct student *p0,*p1,*p2;
p1=head; p0=stud;
if(head==NULL)//空表,直接插入,head等于p0
{head=p0;}
else//循环找到适合的位置
{ while( (p0->num > p1->num) && (p1->next!=NULL) )
{ p2=p1; p1=p1->next;}//记住p1之前的结点
if( p0->num < p1->num )//表头或是中间的位置
{ if( head==p1 ) head=p0;//要插入的位置刚好是表头
else p2->next=p0;//插入中间位置
p0->next=p1; }
else { p1->next=p0;}//插入表尾
}
return(head);
}*/