要求:
把a1,a2,a3,a4,....an分离成
a1,a3,a5,....an,..a4,a2;
代码如下:
//双循环链表
//带头结点的循环链表
#include <iostream>
using namespace std;
typedef int ElemType;
//结点类型定义
typedef struct DoubleListNode
{
ElemType data;
DoubleListNode *prior;
DoubleListNode *next;
}DoubleListNode;
DoubleListNode* CreateList(DoubleListNode *&root,int n)
{
DoubleListNode *last=new DoubleListNode;
last->prior=last->next=NULL;
last=root;
cout<<"请输入结点的信息"<<endl;
int i;
ElemType temp;
for(i=0;i<n;++i)
{
cin>>temp;
DoubleListNode *newnode=new DoubleListNode;
newnode->data=temp;
newnode->prior=newnode->next=NULL;
newnode->next=last->next;
last->next=newnode;
newnode->prior=last;
root->prior=newnode;
last=newnode;
}
return root;
}
void Display(DoubleListNode *root)
{
DoubleListNode *current=root->next;
DoubleListNode *temp=new DoubleListNode;
while (current!=root)
{
temp=current;
cout<<current->data<<" "<<"它的前驱结点是";
if(temp->prior==root)
cout<<temp->prior->prior->data;
else
{
cout<<temp->prior->data;
}
cout<<" "<<"它的后继结点是";
if(temp->next==root)
cout<<temp->next->next->data<<endl;
else
{
cout<<temp->next->data<<endl;
}
current=current->next;
}
}
void Separate(DoubleListNode *&root)
{
DoubleListNode *current=new DoubleListNode;
current->prior=current->next=NULL;
current=root->next;
while (current->next!=root&¤t->next->next!=root)
{
current->next=current->next->next; //跳过偶数结点
current=current->next;
}
if(current->next==root) current->next=root->prior->prior; //如果原数组最后一位是奇数,则连接最后一个偶数
else if(current->next->next==root) //最后一位是偶数,则连接次偶数
{
current->next=root->prior;
}
current=current->next; //此时current定位为最后一个结点,现在开始连偶数点
while (current->prior->prior!=root)
{
current->next=current->prior->prior;
current=current->next;
}
current->next=root;
for(current=root;current->next!=root;current=current->next)
current->next->prior=current;
root->prior=current;
}
int main()
{
DoubleListNode *root=new DoubleListNode;
root->prior=root->next=root;
int n;
cout<<"创建几个结点的双循环链表"<<endl;
cin>>n;
root=CreateList(root,n);
cout<<"链表创建成功"<<endl;
Display(root);
cout<<endl;
Separate(root);
cout<<"分离后的链表"<<endl;
Display(root);
system("pause");
return 0;
}