//刪除結點操作
printf("/nInput the deleted number:");
scanf("%ld",&del_num);
while(del_num!=0)//當輸入學號為0時結束循環
{
head = del(head,del_num);//刪除結點后返回鏈表的頭地址
print(head);//輸出全部結點
printf("Input the deleted number:");
scanf("%ld",&del_num);
}
//插入結點操作
printf("/nInput the inserted number:");
stu=(struct Student*)malloc(LEN);//每插入一個結點需要開辟一個新的結點
scanf("%ld %f",&stu->num,&stu->score);
while(stu->num!=0)//當輸入的學號為0時結束循環
{
head = insert(head,stu);//返回鏈表的頭地址
print(head);
printf("/nInput the inserted number:");
stu = (struct Student*)malloc(LEN);
scanf("%ld %f",&stu->num,&stu->score);
}
return 0;
}
//建立鏈表的函數
struct Student* create()
{
struct Student *head;
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else p2->next=p1;//第一次執行時,這一步是將頭指針指向自身,當n從2起,這一步用于使p2指向下一個元素
p2=p1;//使p2和p1指向同一個存儲區
p1=(struct Student*)malloc(LEN);//開辟動態存儲區,強制返回struct Student類型的指針
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
return (head);
}
//刪除結點的函數
struct Student* del(struct Student* head,long num)
{
struct Student *p1,*p2;
if(head==NULL)
{
printf("List null!/n");
return (head);
}
p1=head;
while(num!=p1->num && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
printf("Delete:%ld/n",num);
n=n-1;
}
else
{
printf("%ld not been found!",num);
}
return (head);
}
//插入結點的函數
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)//找到插入的位置,插入的位置是p1所指向的位置之前,也就是p2指向的位置
{
if(head==p1)head=p0;//如果插入的位置是頭位置之前,則使head指向p0
else p2->next=p0;//如果不是頭位置之前,則使p2的next指針指向插入的數據地址即p0
p0->next=p1;//使p0的next指針指向p1,完成了數據的加入
}
else//插入的學號位置在最后一個
{
p1->next=p0;
p0->next=NULL;
}
n=n+1;//記錄數加一
return(head);
}
//輸出鏈表的函數
void print(struct Student * head)
{
struct Student * p;
printf("Now,These %d records are:/n",n);
p=head;
if(head!=NULL)
do
{
printf("%ld %5.1f/n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
新聞熱點
疑難解答
圖片精選