#include "stdafx.h"
// 这是链表逆序的递归算法
struct Node
{
Node* pNext;
int value;
};
Node* Invert(Node* pHead, Node* pList, Node* &pRHead)
{
if (pList == NULL)
{
pRHead = pHead;
return pHead;
}
else
{
Node* pRevertTail = Invert(pList, pList->pNext, pRHead);
pRevertTail->pNext = pHead;
pHead->pNext = NULL;
return pHead;
}
}
Node* RecursionInvertList(Node* pHead)
{
if(pHead == NULL)
{
return pHead;
}
else
{
Node* pRHead = NULL;
Invert(pHead, pHead->pNext, pRHead);
return pRHead;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
// create a list
Node* pHead = NULL;
Node* pTail = NULL;
for(int index = 0; index < 10; index++)
{
if(pHead == NULL)
{
pHead = pTail = new Node();
pHead->pNext = NULL;
pHead->value = index;
}
else
{
Node* temp = new Node();
temp->pNext = NULL;
temp->value = index;
pTail->pNext = temp;
pTail = temp;
}
}
Node* pTemp = pHead;
while (pTemp)
{
printf("%d ", pTemp->value);
pTemp = pTemp->pNext;
}
printf("\n");
Node* pRHead = RecursionInvertList(pHead);
pTemp = pRHead;
while (pTemp)
{
printf("%d ", pTemp->value);
pTemp = pTemp->pNext;
}
return 0;
}