为什么删除结点需要借助三个辅助结点 并且还使用了pre前驱节点以及q的作用是什么?求解答,感谢
#include <stdio.h>
struct stud_node{
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *Creat_Stu_Doc();
struct stud_node *DeleteDoc(struct stud_node *head,int min_score);
void Ptrint_Stu_Doc(struct stud_node *head);
int main(){
struct stud_node *head;
head = Creat_Stu_Doc();
int x;
scanf("%d",&x);
head = DeleteDoc(head,x);
Ptrint_Stu_Doc(head);
return 0;
}
//思路就是用带头结点的尾插法建立链表,然后删除节点,最后输出。
struct stud_node *Creat_Stu_Doc()
{
struct stud_node *head,p,tail;
int x;
head = (struct stud_node)malloc(sizeof(struct stud_node));
head->next = NULL;//千万记得给头结点初始化后继节点为NULL
tail = head;
scanf("%d",&x);
while(x != 0)
{
p = (struct stud_node)malloc(sizeof(struct stud_node));
p->next = NULL;
p->num = x;
scanf("%s%d",p->name,&p->score);
tail->next = p;//给尾插啊!毕竟尾插法
tail = p;
scanf("%d",&x);
}
tail->next = NULL;
return head;
}
struct stud_node *DeleteDoc(struct stud_node *head,int min_score)
{
struct stud_node *p,*q,pre;
//pre为p的前驱节点
p=head->next;
pre=head;
while(p != NULL)
{
if(p->score<min_score)
{
q=p;
p=p->next;
pre->next = p;
free(q);
}
//需要3个辅助节点 pre指向p的前驱节点,若p所指向的值小于min_score,则删除p(此时借用q来实现删除操作)。
else
{
pre=p;
p=p->next;
}
//若p不小于min_score,让pre和p后移。
}
return head;
}
void Ptrint_Stu_Doc(struct stud_node *head)
{
struct stud_node *p;
for(p=head->next; p != NULL; p = p->next)
{
printf("%d %s %d\n",p->num,p->name,p->score);
}
}