insert 函数编写错了,刚学链表不是很熟,看不出错误。求指教,另外推荐点学习链表指针的书!!!
#include<iostream.h>#include<stdlib.h>
#define LEN sizeof(stud)
typedef struct student
{
int num;
int score;
struct student *next;
} stud;
int n;
void main()
{
stud *creat(void);
void print(stud *head);
stud *insert(stud *head, stud *student);
stud *del(stud *head,int num);
stud *head,*student;
int num;
head=creat();
print(head);
cout<<"input the student";
cin>>student->num>>student->score;
head=insert(head,student);
print(head);
cout<<"input the student'num:";
cin>>num;
head=del(head,num);
print(head);
}
stud *creat(void)
{
stud *head,*p1,*p2;
n=0;
p1=p2=(stud *)malloc(LEN);
head=NULL;
cin>>p1->num>>p1->score;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(stud*)malloc(LEN);
cin>>p1->num>>p1->score;
}
p2->next=NULL;
return head;
}
void print(stud *head)
{
stud *p;
p=head;
if(head!=NULL)
while(p!=NULL)
{
cout<<p->num<<" "<<p->score<<endl;
p=p->next;
}
}
stud *insert(stud *head,stud *student)
{
stud *p1,*p2,*p0;
p0=student;
p1=head;
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;
p0->next=NULL;
}
}
n=n+1;
return(head);
}
stud *del(stud *head,int num)
{
stud *p1,*p2;
p1=head;
if(head==NULL)
{
cout<<"list is empty.";
return(head);
}
while(num!=p1->num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}
if(num==p1->num)
{
if(head==p1)head=p1->next;
else p2->next=p1->next;
cout<<"delete"<<num;
n=n-1;
}
else
cout<<"it is not exsit";
return (head);
}