线性链表的操作问题
这个链表输入:“num 1,score 11”“num 2,score 22”
“num 3,score 33”
“num 4,score 44”
“num 5,score 55”
“num 6,score 66”
后若将“num 1”删除后,再次输出时第一个节点还是会被输出。删除别的都会正常输出。插入节点时,若插入的节点的num比最后一个大,那么这个节点会被插入到倒数第二个位置。。。这是为什么啊。我新手,弄不明白。。这个链表是自己做完后对着谭浩强老师的书改的。若哪位前辈愿意帮忙请指点一下。。谢谢。
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#define len sizeof(struct student)
int n;
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat()
{
struct student *head,*p1,*p2;
n=0;
p1=p2=(struct student *)malloc(len);
head=0;
printf("shu ru xuehao:");
scanf("%d",&p1->num);
printf("shu ru score:");
scanf("%d",&p1->score);
while(p1->num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
p2=p1;
p1=(struct student*)malloc(len);
printf("shuru xuehao:");
scanf("%d",&p1->num);
printf("shuru score:");
scanf("%d",&p1->score);
}
}
p2->next=0;
return (head);
}
void print(struct student *head)
{
struct student *p;
p=head;
if(p==0)
{
printf("kongbuao");
}
else
do
{
printf("num is:%d||score is:%d\n",p->num,p->score);
p=p->next;
}
while(p!=0);
}
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
p1=head;
if(head==0)
{
printf("\n list null \n");
goto end;
}
p1=head;
while(num!=p1->num&&p1->next!=0)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
printf("delete :%d",num);
n=n-1;
}
else
printf("%d not been found!",num);
end:
return head;
}
struct student *insert(struct student *head,struct student *stu)
{
struct student *p1,*p2, *p3;
p3=stu;
p1=head;
if(head==0)
{
head=p3;
p3->next=0;
}
else
{
while(p3->num>p1->num&&p1->next!=0)
{
p2=p1;
p1=p1->next;
}
p2->next=p3;
p3->next=p1;
}
return head;
}
void main()
{
struct student *head;
int num;
struct student *stu;
clrscr();
head=creat();
print(head);
printf("输入要删除的学号:");
scanf("%d",&num);
del(head,num);
print(head);
stu=(struct student*)malloc(len);
printf("输入要插入的学号:");
scanf("%d",&stu->num);
printf("输入要插入的成绩:");
scanf("%d",&stu->score);
insert(head,stu);
print(head);
getch();
}