將以上建立鏈表、刪除結點、插入結點的函數組織在一起,再建一個輸出全部結點的函數,然後用main函數調用它們。
[例1110]鏈表的綜合操作。
#defineNULL0
#defineLENsizeof(structstu)
structstu
{
intnum;
charname[10];
structstu*next;
};
structstu*create()
{
structstu*head,*new,*tail,*p;
intcount=0;
while(1)
{
new=(structstu*)malloc(LEN);
printf("inputNumberandName\n");
scanf("%d%s",&new->num,new->name);
if(new->num==0)
{
free(new);
break;
}
else
if(count==0)
{head=new;tail=new;}
else
{
tail->next=new;
tail=new;
}
count++;
}
tail->next=NULL;
return(head);
}
structstu*delist(structstu*head,intnum)
{
structstu*p0,*p1;
p1=head;
if(head==NULL)/*如為空表,則輸出提示信息*/
{
printf("\nemptylist!\n");
}
else
if(p1->num==num)
head=p1->next;
else
{
while(p1->num!=num&&p1->next!=NULL)
/*當p1不是要刪除的結點,也不是最後一個結點時,繼續循環*/
{
p0=p1;
p1=p1->next;
}/*p0指向當前結點,p1指向下一結點*/
if(p1->num==num)
{
p0->next=p1->next;
/*如果找到待刪結點,則使p0所指結點的指針域指向p1的下一結點*/
printf("Thenodeisdeleted\n");
}
else
printf("Thenodenotbeenfoud!\n");
}
return(head);
}
structstu*insert(structstu*head,structstu*new)
{
structstu*p0,*p1;
p1=head;
if(head==NULL)/*空表插入*/
{
head=new;
new->next=NULL;
}
else
if(new->num
num)
{
new->next=head;
head=new;
}/*在第一結點之前插入*/