#include <iostream>
using namespace std;
template <class T>
class Chain;
template <class T>
class ChainNode
{
friend class Chain<T>;
friend ostream& operator<< <T>(ostream& out, const Chain<T>& x);
private:
T data;
ChainNode<T>* link = 0;
};
//重载 <<
template<class T>
ostream& operator<< (ostream& out, const Chain<T>& x)
{
ChainNode<T>* p;
for (p = x.first; p; p = p->link)
{
out << p->data << "->";
}
return out;
}
template <class T>
class Chain
{
friend ostream& operator<< <T>(ostream& out, const Chain<T>& x);
public:
Chain(){ first = 0; }
Chain<T>& InsertChange(int k);
void split(Chain& A, Chain& B);
private:
ChainNode<T>* first;//指向第一个节点的指针
};
int main()
{
Chain<int> test;
for (int i = 0; i < 10; i++)
{
test.InsertChange(i);
}
cout << test << endl;
Chain<int> A, B;
test.split(A, B);
cout << A << endl;
cout << B << endl;
return 0;
}
template <class T>
Chain<T>& Chain<T>::InsertChange(int k)
{
ChainNode<T>* p = new ChainNode<T>;
ChainNode<T>* q;
p->data = k;
if (!first)
{
first = p;
}
else
{
q = first;
while (q->link)
{
q = q->link;
}
q->link = p;
}
return *this;
}
template<class T>
void Chain<T>::split(Chain& A, Chain& B)
{
ChainNode<T>* p = first;
ChainNode<T>* q = 0;
ChainNode<T>* r = 0;
int i = 0;
while (p)
{
if (first == NULL)
{
return;
}
i++;
if (i % 2 != 0)
{
q = p;
q->link = q;
}
else
{
r = p;
r->link = r;
}
p = p->link;
}
A.first = q;
B.first = r;
return;
}