# 数据结构的C实现_双向循环链表

//编译环境 visual studio 2008，win32 console application.

//DuLNode.c

//双向循环链表
#include <stdio.h>
#include <stdlib.h>
#define    OK 1
#define ERROR 0
typedef char elemType;//元素类型

typedef struct _DuLNode
{
elemType data;
struct _DuLNode *prior;
struct _DuLNode *Next;
}DuLNode,*DuLList;

//获取表长
int DuLNodeLength(DuLNode *L)
{
DuLNode *p=L->Next;
int length=0;
while((p!=NULL)&&(p!=L))
{
p=p->Next;
length++;
}
return length;
}

//获取第pos个位置的元素，若正确获取，返回1，否则返回0
int GetElem(DuLNode *L,int pos)
{
DuLNode *p=L->Next;
int j=1;
while((p!=L)&&j<pos)
{
p=p->Next;
++j;
}
if((p==L)||j>pos){ printf("get postion error\n");return ERROR;}
printf("位置%d处的元素是: %c\n",pos,p->data);
return OK;
}

//获取第pos个位置的元素的指针
DuLList GetElemP(DuLNode *L,int pos)
{
DuLNode *p=L;
int j;
for(j=1;j<=pos;j++)
p=p->Next;
return p;
}

//在带头结点的双向循环链表的第pos个位置前插入元素e
int ListInsert(DuLNode *L,int pos,elemType e)
{
DuLNode *p,*s;

p=GetElemP(L,pos);
if(!p)
return ERROR;//位置不对
if(!(s=(DuLNode *)malloc(sizeof(DuLNode)))) return ERROR;
s->data=e;
s->prior=p->prior;
p->prior->Next=s;
s->Next=p;
p->prior=s;
return OK;
}
//删除第pos个元素，并返回其值
int ListDelete(DuLNode *L,int pos)
{
DuLNode *p;
elemType tmp;
p=GetElemP(L,pos);
if(!p)
return ERROR;
tmp=p->data;
p->prior->Next=p->Next;
p->Next->prior=p->prior;
free(p);
printf("删除第%d个位置的元素，该元素是:%c\n",pos,tmp);
return OK;
}

//正向遍历双向循环链表
void TraverseList(DuLNode *L)
{
DuLNode *p=L->Next;
printf("正向遍历:\n");
while(p!=L)
{
printf("%c ",p->data);
p=p->Next;
}
printf("\n");
}

//逆向遍历双向循环链表
void TraverseBack(DuLNode *L)
{
DuLNode *p=L->prior;//指向尾结点
printf("逆向遍历:\n");
while(p!=L)
{
printf("%c ",p->data);
p=p->prior;
}
printf("\n");
}

main()
{
DuLNode *L=(DuLNode *)malloc(sizeof(DuLNode));
L->Next=L->prior=L;//循环链表
ListInsert(L,1,'a');
ListInsert(L,2,'b');
ListInsert(L,3,'c');
ListInsert(L,4,'d');
printf("表长为%d\n",DuLNodeLength(L));
TraverseList(L);
GetElem(L, 1);
GetElem(L, 2);
GetElem(L, 3);
ListDelete(L,2);
TraverseList(L);
TraverseBack(L);
} 

04-07 1667

11-15 2151

08-18 683

04-11 7437

12-14 2153

04-11 1317

09-10 1490

10-30 3017

09-20 951

11-11 683