数据结构--双向循环链表c语言实现

XList.h如下:

#ifndef __LIST_H
#define __LIST_H

typedef struct LNode
{
	int data;
	struct LNode* next;
	struct LNode* pre;
}LNode, *List;

void InitList(List list);//初始化化单链表

void Insert_Head(List list, int var);//头插节点

void Insert_Tail(List list, int var);//尾插节点

LNode *Search(List list, int key);//查找key

LNode *SearchPre(List list, int key);//查找key的前驱

bool Delete(List list, int key);//删除key

bool isEmpty(List list);//是否为空

int Length(List list);//返回链表的数据节点个数

void Show(List list);//打印

void Destroy(List list);//删除list所有数据节点


#endif


XList.c如下:

</pre><pre name="code" class="cpp">#include"XList.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

static LNode* BuyNode(int val)
{
	LNode *p = (LNode*)malloc(sizeof(LNode));
	assert(p != NULL);
	p->data = val;
	p->next = NULL;
	p->pre = NULL;
	return p;
}

void InitList(List list)//初始化化单链表
{
	assert(list);
	list->next = list;
	list->pre = list;
}

void Insert_Head(List list, int var)//头插节点
{
	LNode *p = BuyNode(var);
	LNode *tmp = list;
	p->next = list->next;
	//list->next->pre = p;//多余了
	p->pre = list;
	list->next = p;
	while (tmp->next != list)
		tmp = tmp->next;
	list->pre = tmp;
}

void Insert_Tail(List list, int var)//尾插节点
{
	LNode *last = list;
	LNode *p = BuyNode(var);
	while (last->next != list)
		last = last->next;
	last->next = p;
	p->pre = last;
	p->next = list;
	list->pre = p;
}

LNode *Search(List list, int key)//查找key
{
	LNode* p = list->next;
	while (p!= list)
	{
		if (p->data == key)
			return p;
		p = p->next;
	}
	return NULL;
}

LNode *SearchPre(List list, int key)//查找key的前驱
{
	LNode* p = list->next;
	while (p!= list)
	{
		if (p->data == key)
			return p->pre;
		p = p->next;
	}
	return NULL;
}

bool Delete(List list, int key)//删除key
{
	LNode* p = Search(list, key);
	if (p == NULL)
		return false;
	p->next->pre = p->pre;
	p->pre->next = p->next;
	free(p);
	return true;
}

bool isEmpty(List list)//是否为空
{
	if (list->next = list)
		return true;
	return false;
}

int Length(List list)//返回链表的数据节点个数
{
	int count = 0;
	LNode* p = list;
	while (p->next != list)
	{
		count++;
		p = p->next;
	}
	return count;
}

void Show(List list)//打印
{
	LNode* p = list;
	while (p->next != list)
	{
		printf("%d ", p->next->data);
		p = p->next;
	}
	printf("\n");
}

void Destroy(List list)//删除list所有数据节点
{
	LNode* p = list->next;
	LNode* t = p;
	while (p!= list)
	{
		p->next->pre = p->pre;
		p->pre->next = p->next;
		t = p;
		free(t);
	}
	free(list);
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值