c语言双向链表的增、删、改、查

双向链表与单向链表相比,多了一个前驱(指向前一个节点的指针,初始化多加一个前驱指针即可)

双向链表增、删、改、查demon

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


typedef struct double_list{
	char* data;
	struct double_list *next; //后继---指向下个节点
	struct double_list *prev;//前驱---指向上一个节点
}d_list;

typedef struct double_list* double_point;

//1.创建一个双向链表
double_point creat_list()
{
	double_point double_head=NULL;
	double_head=(double_point)malloc(sizeof(d_list));//为头节点申请空间
	if(NULL == double_head)
	{
		printf("malloc error\n");
		return NULL;
	}

	double_head->next=double_head->prev=NULL;
	return double_head;
}

//2.向双向链表插入数据
void insert_doule_list(double_point list,char *data)
{
	if(list == NULL)
	{
		printf("链表大小为0,插入失败\n");
		return;
	}
	double_point tmp_head=list;//tmp_head是指向list的头节点

//尾插入
	while(tmp_head->next != NULL)
	{
		tmp_head=tmp_head->next;
	}

	double_point insert_point=(double_point)malloc(sizeof(d_list));
	insert_point->data=data;
	insert_point->prev=tmp_head;
	insert_point->next=tmp_head->next;
	tmp_head->next=insert_point;
	return ;
}

//3.删除指定的数据
void delet_doule_list(double_point list,char *data)
{
	if(list == NULL)
	{
		printf("链表大小为0,插入失败\n");
		return;
	}
	
	double_point tmp_head=list;//tmp_head是指向list的头节点
	while(tmp_head->next != NULL)
	{
		if(tmp_head->data!=NULL)
		{
			if(0==strcmp(tmp_head->data,data))
				break;
		}
		tmp_head=tmp_head->next;
	}

	tmp_head->prev->next=tmp_head->next;
	tmp_head->next->prev=tmp_head->prev;
	free(tmp_head);
	return;
}

//4.替换某个数据
void update_doule_list(double_point list,char *data,char *updata)
{
	if(list == NULL)
	{
		printf("链表大小为0,插入失败\n");
		return;
	}
	
	double_point tmp_head=list;//tmp_head是指向list的头节点
	while(tmp_head->next != NULL)
	{
		if(tmp_head->data!=NULL)
		{
			if(0==strcmp(tmp_head->data,data))
				break;
		}
		tmp_head=tmp_head->next;
	}

	tmp_head->data=updata;
	return;
}


//遍历链表
void show_list(double_point list)
{
	double_point p=list->next;
	while(p!=NULL)
	{
		printf("正向访问%s\t ",p->data);
		if(p->prev->prev!=NULL){
			printf("反向访问 :%s",p->prev->data);
		}
		p=p->next;	
		printf("\n");
	}
	return ;
}



int main()
{
	double_point list=creat_list();
	insert_doule_list(list, "hello");
	insert_doule_list(list, "world");
	insert_doule_list(list, "!");
	show_list(list);
	printf("\n删除后数据为:\n");
	delet_doule_list(list,"world");
	show_list(list);

	printf("\n更改后数据为:\n");
	update_doule_list(list,"!","world");
	show_list(list);
	return 0;
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值