链表--删除指定值(单链表,双链表)

定义结构体:

  #include<stdio.h>
    #include<malloc.h>
    typedef struct _STU
    {
    	int id;
    struct _STU* next;
    }STU,*PSTU;

头插

void Inserthead(PSTU* phead,int id)
{
	PSTU pnew = (PSTU)malloc(sizeof(STU));
	pnew->id = id;
	pnew->next = *phead;
	  *phead=pnew;
}

尾插

void Inserttail(PSTU* phead,int id)
{
	
	if (*phead == NULL)
	{
		Inserthead(phead, id);
	}
	else
	{
		PSTU ppos = *phead;
		while (ppos->next != NULL)
		{
			ppos = ppos->next;
		}
		PSTU pnew = (PSTU)malloc(sizeof(STU));
		pnew->id = id;
		pnew->next = NULL;
		ppos->next = pnew;
	}
	}

头删

void Deletehead(PSTU* phead)
{
	if (*phead != NULL)
	{
		PSTU ppos = *phead;
		*phead = ppos->next;
		free(ppos);
		ppos = NULL;
	}
}

先删除与该值相同的第一个数

PSTU Deletefirstvalue(PSTU ppos, int id)
{
	while (ppos->next != NULL&&ppos->next->id != id)  //当链表不是一个结点并且头指针的next的id 不等于id时,往后循环
	{
		ppos = ppos->next;
	}
	if (ppos->next != NULL)
	{
		PSTU t = ppos->next;
		ppos->next = t->next;
		free(t);
		t = NULL;
		return ppos;
	}
	else
	{
		return NULL;
	}
}   

删除值函数

void Deletebyvalue(PSTU *phead,int id)
{
	while ((*phead)->id==id)
	{
		Deletehead(phead);  //当头指针的id和输入i的d相同时,删除头指针
	}
	PSTU ppos = *phead;  //让位置指向头指针
	ppos=Deletefirstvalue(ppos,id);//删除第一个与它相同的id,让位置停留在已删id的前一位
	while (ppos != NULL)   //继续找下一个不为空的地址
	{
		ppos=Deletefirstvalue(ppos, id);   //调用函数,每次让位置停留在已删id的前一位
	}
}

输出函数

void show(const PSTU phead)
{
	
	 PSTU ppos = phead;
	while (ppos != NULL)
	{
		printf("%d,\n", ppos->id);
		ppos = ppos->next;
	}
}

主函数

int main()
{
	PSTU head1 = NULL; PSTU head2 = NULL;
	Inserttail(&head1, 1);
	Inserttail(&head1, 2);
	Inserttail(&head1, 10);
	Inserttail(&head1, 8);
	Inserttail(&head1, 9);
	/*PSTU ppos = head1;
	Deletebyvalue(&head1,1);*/      // 单链表head1时,删除链表中与1相同的元素
	
	Inserttail(&head2, 1);
	Inserttail(&head2, 2);
	Inserttail(&head2, 9);
	Inserttail(&head2, 3);
	Inserttail(&head2, 5);
	PSTU ppos = head2;    
	while (ppos!= NULL)
	{
		Deletebyvalue(&head1,ppos->id);    //删除与链表1中与链表2相同的id
		ppos = ppos->next;
	}
	show(head1);

	 return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值