代码的作用是将元素用头插的方法插入简历的链表中,然后输入一个数值,删掉链表中与其相等的结点。
代码逻辑:
在主函数中建立两个链表,并用头插的方法插入两组数据,调用deletehead函数对其操作(第一个结点和最后一个结点不做处理);用pPos指向第一个结点,t指向pPos的下一个结点,若其满足删除条件,令pPos->next指向t->next,free(t)并令t=NULL。然后令pPos所指向的结点的next指向pPos->next->next如图示红线。
最后处理第一个节点和最后一个结点,若第一个结点需要删除,则调头删函数Deletehead对其操作,然后遍历链表至倒数第二个结点,若pPos->next->score==num则调头删函数删除最后一个结点,完成操作。
同样,对另一个链表也可以进行此操作以删除其中id对应的结点。
#include<stdio.h>
#include<malloc.h>
typedef struct _Stu
{
int id;
int score;
struct _Stu* next;
}Stu,*PStu;
void Inserthead(PStu* pphead, int id, int score)
{
PStu pNew = (PStu)malloc(sizeof(Stu));
pNew->id = id;
pNew->score = score;
pNew->next = *pphead;
*pphead = pNew;
}
void DeleteHead(PStu* ppHead)
{
if (*ppHead != NULL)
{
PStu pPos = *ppHead;
*ppHead = pPos->next;
free(pPos);
pPos = NULL;
}
}
void deletehead(PStu* pphead, int num)
{
PStu pPos = NULL;
PStu t = NULL;
pPos = *pphead;
while (pPos!=NULL&&pPos->next != NULL)
{
if (pPos->next->score == num)
{
t = pPos->next;
pPos->next = pPos->next->next;
free(t);
t = NULL;
}
pPos = pPos->next;
}
if ((*pphead)->score == num)
{
DeleteHead(pphead);
}
pPos = *pphead;
while (pPos->next->next != NULL)
{
pPos = pPos->next;
}
if(pPos->next->score==num)
DeleteHead(&(pPos->next));
}
void show(PStu phead)
{
PStu pPos = phead;
while (pPos != NULL)
{
printf("%d %d\n", pPos->id, pPos->score);
pPos = pPos->next;
}
printf("*************************************\n");
}
int main()
{
PStu head1 = NULL;
PStu head2 = NULL;
Inserthead(&head1, 1, 45);
Inserthead(&head1, 4, 66);
Inserthead(&head1, 5, 72);
Inserthead(&head1, 9, 48);
Inserthead(&head2, 2, 95);
Inserthead(&head2, 3, 86);
Inserthead(&head2, 6, 82);
Inserthead(&head2, 7, 98);
deletehead(&head1, 66);
show(head1);
show(head2);
}
所得到的结果为: