/************************************************************************/
/* 7、怎样把一个链表掉个顺序 */
/************************************************************************/
class LinkNode
{
public:
LinkNode(int data, LinkNode* next = NULL): m_data(data), m_next(next)
{}
int m_data;
LinkNode* m_next;
};
typedef LinkNode* Link;
//前插法
void linkReverse(Link& head)
{
if(!head || !head->m_next)
return;
LinkNode* pNode = head->m_next;
head->m_next = NULL;
while(pNode)
{
//pNode插到前面
LinkNode* pTemp = pNode->m_next;
pNode->m_next = head;
head = pNode;
pNode = pTemp;
}
}
LinkNode* createLink(int size)
{
if(size == 0)
return NULL;
LinkNode* head = new LinkNode(0);
LinkNode* pNode = head;
for(int i = 1; i < size; ++i)
{
pNode->m_next = new LinkNode(i);
pNode = pNode->m_next;
}
return head;
}
void deleteLink(LinkNode* head)
{
while(head)
{
LinkNode* pNode = head->m_next;
delete head;
head = pNode;
}
}
void printLink(LinkNode* head)
{
//打印
LinkNode* pNode = head;
while(pNode)
{
cout << pNode->m_data << "\t";
pNode = pNode->m_next;
}
cout << endl;
}
void testOfReverseLink()
{
const int size = 10;
LinkNode* head = createLink(size);
cout << "befor reverse: " << endl;
printLink(head);
linkReverse(head);
cout << "after revers:" << endl;
printLink(head);
deleteLink(head);
}