链表的按值删除

代码的作用是将元素用头插的方法插入简历的链表中,然后输入一个数值,删掉链表中与其相等的结点。
代码逻辑:
在主函数中建立两个链表,并用头插的方法插入两组数据,调用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);
}

所得到的结果为:
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值