设单循环链表L1,对其遍历的结果是x1,x2,……xn。将该循环链表拆分成两个单循环链表L1和L2,使得L1中含有原L1表中序号为奇数的节点,L2中含有原L1表中序号为偶数的节点;
#include <iostream>
#include<list>
using namespace std;
template <class T>
struct Node
{
T data;
Node<T>* next;
};
template <class T>//尾插建立循环单链表
Node<T>* creat_back( Node<T> * first,int len)
{
Node<T>* r=first;
for( int i=0; i<len; i++)
{
int data;
cin>>data;
Node<T>* pnew=new Node<T>;
pnew->data=data;
pnew->next=r->next;
r->next=pnew;
r=pnew;
}
r->next=first;
return first;
}
template <class T>//输出链表循环单链表
void show(Node<T>* first)
{
Node<T>* p=first->next;
while(p!=first)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl<<endl;
}
template <class T>
void DePatch(Node<T>* L1,Node<T>* L2 )//将单循环链表L1拆成L1和L2两个单循环链表
{
L2->next=L2;
Node<T>* cur=L1->next;
L1->next=NULL;
Node<T>* r=L1;
Node<T>* r2=L2;
int i=1;
Node<T>* u=NULL;
while(cur!=L1)
{
if(i%2==1)
{
u=cur->next;
cur->next=L1;
r->next=cur;
r=cur;
cur=u;
i++;
}
else
{
u=cur->next;
cur->next=L2;
r2->next=cur;
r2=cur;
cur=u;
i++;
}
}
}
int main()
{
Node<int>* first=new Node<int>;
first->next=NULL;
Node<int>* L2=new Node<int>;
L2->next=NULL;
first= creat_back(first,5);
DePatch(first,L2);
show(first);
show(L2);
return 0;
}