第一個方法:
/*根據姓名刪除鏈表的中的學生記錄*/
void deleteByName(struct STUDENT * head)
{
struct STUDENT *p,*q;
char name[20];
if(head==NULL)
{
printf("鏈表為空。\n");
return;
}
printf("請輸入要刪除的學生的姓名:");
scanf("%s",name);
for(p=head->next,q=head;p!=NULL;p=p->next,q=q->next)
{
if(strcmp(p->name,name)==0)
{
q->next=p->next;
}
}
if(p==NULL)
printf("要刪除的學生不存在。");
else
free(p);
}
這個方法主要是 q->next=p->next ,然後釋放 p結點所占的內存空間。
第2個方法:
/***************
函數功能:
刪除出勤學生姓名
返回:指向鏈表表頭的指針
/***************/
struct student * del_message(struct student* head)
{
FILE* fp;
struct student* pointer,*temp; //p指向新的結點 temp指針為臨時結點
InputBox(stu.ID,11,"請輸入要刪除學生姓名的學號");
fp=fopen("student.txt","wb+");
pointer=head->next; //從頭結點開始遍歷指向下一個節點
while(pointer!=NULL) //如果遍歷不到空數據的話就一直遍歷
{
if(strcmp(pointer->ID,stu.ID)==0) //找到要刪除的結點
{
temp=pointer; //將找到的結點賦值給臨時temp結點變量
pointer=pointer->next; // 將p結點的下一個節點 賦值給p結點
free(temp); //釋放臨時temp結點所占內存
while(pointer!=NULL) //將剩下的結點寫入
{
fwrite(pointer,sizeof(struct student),1,fp);
pointer=pointer->next;
}
break;
}
fwrite(pointer,sizeof(struct student),1,fp); //開始遍歷鏈表結點,並寫入文件
pointer=pointer->next; //p指針指向新的結點(下一個結點)
}
fclose(fp);
outtextxy(220, 200, "刪除出勤學生成功!");
return head;
}
這個方法先找到p結點,也就是要刪除的結點,然後將其賦值給一個臨時的temp結構變量,然後p結點的下一個結點賦值給p結點,最後釋放temp結點所占用的內存。
temp=pointer; //將找到的結點賦值給臨時temp結點變量
pointer=pointer->next; // 將p結點的下一個節點 賦值給p結點
free(temp); //釋放臨時temp結點所占內存
第二個方法是是從文件中讀寫鏈表結構。
不知道兩種方法是否一樣?