// 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;
}
c双向链表的实现
最新推荐文章于 2023-06-20 22:03:45 发布