为什么删除结点需要借助三个辅助结点 并且还使用了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);}}
首先,你这是一个链表
链表不是顺序表,你只能通过next去找到它的下个节点的地址
当你要删除链表中的一项,你需要将它的上一项指向它的下一项,让链表不要断掉
那么你至少需要上个节点的地址,本节点地址,下个节点的地址
其中下个节点可以直接用本节点.next访问,所以这里只需要2个指针,pre和p
由于最后要删除掉本节点,那么当本节点的指针移动了,就删错节点了,所以需要一个额外的指针先记录下本节点的地址,q就是用来记录的