链表翻转的递归算法

#include "stdafx.h"
 
// 这是链表逆序的递归算法
 
struct Node
{
	Node* pNext;
	int value;
};
 
Node* Invert(NodepHeadNodepListNode* &pRHead)
{
	if (pList == NULL)
	{
		pRHead = pHead;
		return pHead;
	}
	else
	{
		Node* pRevertTail = Invert(pListpList->pNext, pRHead);
		pRevertTail->pNext = pHead;
		pHead->pNext = NULL;
		return pHead;
	}
}
 
Node* RecursionInvertList(NodepHead)
{
	if(pHead == NULL)
	{
		return pHead;
	}
	else
	{
		Node* pRHead = NULL;
		Invert(pHeadpHead->pNext, pRHead);
		return pRHead;
	}
}
 
int _tmain(int argc_TCHARargv[])
{
	// 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;
}
posted @ 2014-04-21 22:56  临风远望  阅读(206)  评论(0编辑  收藏  举报