双向链表的增删改查

本文介绍在linux环境中,用c语言实现双向循环链表的尾插,中间某处插入,删除以及查询的操作。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>

typedef struct node
{
	int data;
	struct node *prev;
	struct node *next;

} ST;
//初始化链表 
void init_dlinklist(ST *p)
{
	p->data = 0;
	p->prev = p->next = p;

}
//尾插
bool insert_tar(ST*p,int new_data)
{
	ST*pnew = (ST*)malloc (sizeof(ST));
	pnew ->data = new_data;
	pnew ->prev = pnew->next = pnew;

	pnew ->prev = p->prev;
	pnew ->next = p;
	p->prev->next = pnew;
	p->prev = pnew;
	
}
//中间插入
bool insert_tar_middle(ST*p,int tar,int new_data)
{

	ST*pnew = (ST*)malloc (sizeof(ST));
	pnew ->data = new_data;

	ST*pcur;
	for(pcur = p->next;pcur!=p;pcur = pcur->next)
	{
		if(pcur->data == tar)//************************遍历链表寻找要插入的位置
		{
			pnew ->next = pcur->next;
			pnew->prev = pcur;
			pcur ->next = pnew;
		}
	}
}
//删除
bool delete_tar(ST*p,int tar)
{
	ST*pcur;
	for (pcur = p->next;pcur!=p;pcur = pcur->next)//***遍历链表寻找要删除的数据
	{
		if (pcur->data == tar)
		{
			pcur->prev->next = pcur->next;
			pcur->next->prev = pcur->prev;
			free(pcur);
		}
	}

}
//输出
bool print_st(ST*p)
{
	ST*pcur;
	for(pcur = p->next;pcur!=p;pcur = pcur->next)
	{
		printf("%d<=====>",pcur->data);
	}
	putchar('\n');
}
int main(int argc, const char *argv[])
{
	ST head;
	init_dlinklist(&head);
	insert_tar(&head,10);
	insert_tar(&head,20);
	insert_tar(&head,10);
	insert_tar(&head,40);
 	insert_tar_middle(&head,30,99);
	delete_tar(&head,10);
	print_st(&head);
		return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值