数据结构课程中循环双链表的简单实现以及一些简单操作的测试。
//循环双链表的简单实现测试结果如下:
#include <iostream>
#include <stdlib.h>
#define ElemType char
#define MaxSize 50
using namespace std;
//结构定义
typedef struct ListNode
{
ElemType data;
struct ListNode *next;
struct ListNode *prior;
}DLinkList;
//头插法建立循环双链表
void CreateCDListF(DLinkList *&L,ElemType a[],int n)
{
DLinkList *s;
int i;
L=(DLinkList*)malloc(sizeof(DLinkList));
L->next=L->prior=L;
for(i=0;i<n;i++)
{
s=(DLinkList*)malloc(sizeof(DLinkList));
s->data=a[i];
s->next=L->next;
L->next->prior=s;
L->next=s;
s->prior=L;
}
}
//尾插法建立单链表
void CreateCDListR(DLinkList *&L,ElemType a[],int n)
{
DLinkList *s,*r;
int i;
L=(DLinkList*)malloc(sizeof(DLinkList));
L->next=L->prior=L;
r=L;
for(i=0;i<n;i++)
{
s=(DLinkList*)malloc(sizeof(DLinkList));
s->data=a[i];
r->next=s;
s->prior=r;
r=s;
s->next=L;
L->prior=s;
}
}
//查找元素
int FinCDLinkList(DLinkList *L,ElemType e)
{
int n=1;
DLinkList *p=L->next;
while(p!=L&&p->data!=e)
{
p=p->next;
n++;
}
if(p==L)
return 0;
else
return n;
}
//插入元素
int Insert(DLinkList *&L,ElemType e,int i)
{
int n=1;
if(n<0||L==NULL)
return 0;
DLinkList *pre=L,*p=pre->next,*s;
while(p!=L&&n!=i)
{
pre=p;
p=p->next;
n++;
}
if(p==L&&n!=i)
return 0;
else
{
s=(DLinkList*)malloc(sizeof(DLinkList));
s->data=e;
s->next=pre->next;
p->prior=s;
pre->next=s;
s->prior=pre;
return 1;
}
}
//删除元素
int Delete(DLinkList *&L,ElemType e)
{
if(L==NULL)
return 0;
DLinkList *pre=L,*p=pre->next;
while(p!=L&&p->data!=e)
{
pre=p;
p=p->next;
}
if(p==L)
return 0;
else
{
pre->next=p->next;
p->next->prior=pre;
free(p);
return 1;
}
}
//测试函数
int main()
{
ElemType a[10]={'d','g','w','v','h','k','e','w','t','u'};
DLinkList *L ;
//CreateCDListF(L,a,10);
CreateCDListR(L,a,10);
DLinkList *p=L->next;
cout<<"构造好之后的链表中的元素为:";
while(p!=L)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
cout<<"h在链表的位置为:"<<FinCDLinkList(L,'h')<<endl;
Insert(L,'p',4 );
cout<<"在位置4处插入'p'后链表的元素为:";
p=L->next;
while(p!=L)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
Delete(L,'t');
cout<<"删除元素't'之后的链表元素为:";
p=L->next;
while(p!=L)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}