双向链表与单向链表相比,多了一个前驱(指向前一个节点的指针,初始化多加一个前驱指针即可)
双向链表增、删、改、查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;
}
运行结果: