//双向循环列表
typedef struct dnode
{
int data;
struct dnode *preNode,*nextNode;
}dCycleLink;


完成两个操作:

1 插入 dCycleLink* insertData(dCycleLink *head,int num,int data);

2 删除 dCycleLink* deleteData(dCycleLink*head,int data);


实际上,双向循环列表的操作和单向的差不多的,只是 需要多考虑 prenode的这样的一个元素就可以了。好了,上代码


1 插入

// 找到结点之后;
dCycleLink* insertData( dCycleLink *head,int num,int data)
{
assert(head!=NULL);
dCycleLink *p=head;
int count=1;

while(p!=NULL&&count<num)
{
count++;
p=p->nextNode;
}

if(count==num)
{
dCycleLink *s=(dCycleLink*)malloc(sizeof(dCycleLink));
if(s!=NULL&&p!=NULL)
{
s->data=data;
s->preNode=p; //1
p->nextNode->preNode=s; //2
s->nextNode=p->nextNode; //3
p->nextNode=s; //4
}
cout<<"插入成功!!!"<<endl;
printCycleLink(head);
}
else
{
cout<<"插入失败!!!"<<endl;
}
return head;
}


2 删除

dCycleLink* deleteData( dCycleLink*head,int data )
{
assert(head);
dCycleLink* p=head;

while(p!=NULL&&p->data!=data)
{
p=p->nextNode;
}
//跳出循环:1 p为NULL,没有找到 2 p->data=data,找到结果了
if(p->data==data)
{
p->preNode->nextNode=p->nextNode;
p->nextNode->preNode=p->preNode;
free(p);
p=NULL;
cout<<"找到了,删除成功!"<<endl;
printCycleLink(head);
}
else
{
cout<<"没有找到,删除失败!"<<endl;
}
return head;
}


3 测试代码

int main()
{
int num;
cout<<"请输入要创建的节点的个数n:";
cin>>num;
dCycleLink* cycleLink;
cycleLink=createDoublyCycleLink(num);
cycleLink=insertData(cycleLink,2,10);
cycleLink=deleteData(cycleLink,2);
return 0;
}



dCycleLink* createDoublyCycleLink( int n )
{
int xValue;
dCycleLink *head,*p,*pre;

cout<<"请输入第1个数字: ";
cin>>xValue;
p=(dCycleLink*)malloc(sizeof(dCycleLink));
p->data=xValue;
p->preNode=NULL;
p->nextNode=NULL;
head=p;
pre=p;

for(int i=1;i<n;i++)
{
cout<<"请输入第"<<i+1<<"个数字: ";
cin>>xValue;
p=(dCycleLink*)malloc(sizeof(dCycleLink));
p->data=xValue;
p->nextNode=NULL;

p->preNode=pre; //体现双向的 特点
pre->nextNode=p;
pre=p;
}

printCycleLink(head);
return head;
}


void printCycleLink(dCycleLink *head )
{
dCycleLink* pNode=head;

cout<<"这个链表的数据是:"<<endl;
while(pNode)
{
cout<<pNode->data<<endl;
pNode=pNode->nextNode;
}
}