/*******************************************
双链表操作:list_serach list_insert list_delete
相关伪代码:
//在链表L中查找具有关键字k的元素x
list_search(L,k)
x=head[L]
while x != NIL and key[x]!=k
do x <—— next[x]
return x
//将设置了关键字的新元素x插入链表
list_insert(L,x)
next[x] <—— head[L]
if head[L] != NIL
then prev[head[L]] <—— x
head[L] <—— x
pre[x] <—— NIL
//从链表中删除元素x
list_delete(L,x)
if pre[x] != NIL
then next[prev[x]] <—— next[x]
else head[L] <—— next[x]
if next[x] != NIL
then prev[next[x]] <—— prev[x]
*******************************************/
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node *prev;
struct node *next;
int data;
};
//搜索节点的值为k的节点
struct node* list_search(struct node *L,int k)
{
struct node *rval=L;
while(rval!=NULL && rval->data!=k)
rval=rval->next;
return rval;
}
//在链表头部插入节点x,注意传入的参数是指针的指针**L
void list_insert(struct node **L,struct node *x)
{
x->next=*L;
if((*L)!=NULL)
(*L)->prev=x;
(*L)=x;
x->prev=NULL;
}
//删除x节点
int list_delete(struct node *L,struct node *x)
{
struct node *tmp=L;
for(;tmp!=NULL;tmp=tmp->next){
if(tmp==x){
if(x->prev != NULL)
x->prev->next=x->next;
else
(L)=x->next;
if(x->next != NULL)
x->next->prev=x->prev;
return 0;
}
}
return -1;//代表没有找到节点x
}
//创建一个双链表
struct node * init_list()
{
struct node *L=(struct node*)malloc(sizeof(struct node));
return L;
}
//释放链表资源
void finit_list(struct node *L)
{
if(L==NULL)
return;
struct node *p=L->next;
struct node *tmp;
while(p!=NULL){
tmp=p;
p=p->next;
free(tmp);
}
if(L) free(L);
}
int main()
{
struct node *list=init_list();
if(list==NULL)
return 1;
list->data=1024;
int i;
struct node *tmp;
for(i=0;i<5;++i){
tmp=(struct node*)malloc(sizeof(struct node));
if(tmp!=NULL){
tmp->data=i;
list_insert(&list,tmp);
}
}
for(tmp=list;tmp!=NULL;tmp=tmp->next)
printf("%d ",tmp->data);
list_delete(list,list_search(list,3));
for(tmp=list;tmp!=NULL;tmp=tmp->next)
printf("%d ",tmp->data);
//释放链表资源
finit_list(list);
}
(九)双链表
最新推荐文章于 2024-05-04 20:56:25 发布