//雙向循環列表
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;
}
}