(九)双链表

/*******************************************
双链表操作: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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值