c双向链表的实现

// DBList.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
//双向链表的实现
//双向链表每个节点都带一个前驱指针和后续指针,分别为LLink,RLink;

typedef int DataType;

//双向链表数据结构
typedef struct Node
{
	DataType data;
	struct Node *LLink;		//前驱指针
	struct Node *RLink;		//后继指针

}DBLNode,*DBList;


//初始化双向链表
bool InitDBList( DBList &first )
{
	first = new DBLNode();
	if( NULL == first ) return false;
	first->LLink = first;
	first->RLink = first;
	return true;
}

//查找算法
DBList Serach( DBList &first, DataType x, int opt )
{
	DBList  p = (opt == 0)?first->LLink:first->RLink;
	if( p == first ) return NULL;
	while( p != first && p->data != x ) //p != first 防止没有X元素造成死循环
	{
		p = (opt == 0 )?p->LLink:p->RLink;
	}
	return (p != first)?p: NULL;
}

//定位算法
DBList Locate( DBList &first, int i, int opt )
{
	if( first == NULL || i < 0 ) return NULL;
	DBList p = first;
	for( int j = 0;j < i; j++ )
	{
		p = ( opt == 0 )? p->LLink:p->RLink;
		if( p == first ) return NULL;
	}

	return p;
}

//插入算法
bool Insert( DBList &first,int i, DataType x, int opt )
{
	DBList p = Locate( first, i-1, opt );
	if( NULL == p ) return false;
	DBList newNode = new DBLNode();
	if( NULL == newNode )return false;
	newNode->data = x;
	if( opt )
	{
		p->RLink->LLink = newNode;
		newNode->LLink = p;
		newNode->RLink = p->RLink;
		p->RLink = newNode;
	}else
	{
		newNode->RLink = p;
		p->LLink->RLink = newNode;
		newNode->LLink = p->LLink;
		p->LLink = newNode;
		

	}
	return true;
}

//输出所有双向链表节点
void Output( DBList &first, int opt )
{
	DBList p = ( opt == 0 )? first->LLink:first->RLink;
	if( first == p ) return;
	while( p != first )
	{
		printf("%d\n",p->data);
		p = ( opt == 0)? p->LLink:p->RLink;
	}

}




int _tmain(int argc, _TCHAR* argv[])
{
	DBList first;
	InitDBList(first);

	Insert(first, 1, 1,1 );
	Insert(first, 2, 2,1 );
	Insert(first, 3, 3,1 );
	Insert(first, 4, 5,1 );
	Insert(first, 5, 6,1 );
	Insert(first, 6, 7,1 );
	Insert(first, 7, 8,1 );
	
	Output(first,1);

	getchar();
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值