不开辟新空间反转单链表(递归版本)

写的还是很坑的,今天状态奇差

ListNode* ReverseList(ListNode* pHead, ListNode*& pNewHead )
{
	if ( NULL == pHead )
		return NULL;

	ListNode* pPrev = NULL;

	if ( NULL != pHead->m_pNext )
		pPrev = ReverseList( pHead->m_pNext, pNewHead );
	else//注意得保存下新的头
		pNewHead = pHead;

	if ( NULL != pPrev )//注意递归第一次,pPrev为NULL,所以得加条件判断
		pPrev->m_pNext = pHead;

	return pHead;
}


测试:
#include <iostream>
using namespace std;


struct ListNode{
	int m_nKey;
	ListNode* m_pNext;

	ListNode( ListNode* pNext, int value )
		: m_pNext( pNext )
		, m_nKey( value )
	{}
};


void push_back( ListNode** pHead, int value );
ListNode* Find( ListNode* pListHead, int value );
ListNode* ReverseList(ListNode* pHead, ListNode*& pNewHead );


int main( )
{
	ListNode* pHead = NULL;

	//push_back( &pHead, 1 );

	/*push_back( &pHead, 1 );
	push_back( &pHead, 2 );*/

	//push_back( &pHead, 1 );
	//push_back( &pHead, 2 );
	//push_back( &pHead, 3 );
	//push_back( &pHead, 4 );


	ListNode* pNewHead = NULL;
	ReverseList( pHead, pNewHead );

	if ( NULL != pHead )						//坑1
		pHead->m_pNext = NULL;

	while ( NULL != pNewHead ){
		//坑2.小心别 NULL != pNewHead  这样会遗漏最后一个结点
		cout << pNewHead->m_nKey << " ";
		pNewHead = pNewHead->m_pNext;
	}

	cout << endl;

	return 0;
}


void push_back( ListNode** pHead, int value )
{
	if ( NULL == pHead )
		return;

	ListNode* pNewNode = new ListNode( NULL, value );

	if ( NULL == *pHead ){
		*pHead = pNewNode;
		return;
	}

	ListNode* pNode = *pHead;

	while ( NULL != pNode->m_pNext )
		pNode = pNode->m_pNext;

	pNode->m_pNext = pNewNode;
}

ListNode* Find( ListNode* pListHead, int value )
{
	if ( NULL == pListHead )
		return NULL;

	ListNode* pNode = pListHead;

	while ( NULL != pNode && value != pNode->m_nKey )
		pNode = pNode->m_pNext;

	if ( NULL == pNode )
		return NULL;

	return pNode;
}


ListNode* ReverseList(ListNode* pHead, ListNode*& pNewHead )
{
	if ( NULL == pHead )
		return NULL;

	ListNode* pPrev = NULL;

	if ( NULL != pHead->m_pNext )
		pPrev = ReverseList( pHead->m_pNext, pNewHead );
	else//注意得保存下新的头
		pNewHead = pHead;

	if ( NULL != pPrev )//注意递归第一次,pPrev为NULL,所以得加条件判断
		pPrev->m_pNext = pHead;

	return pHead;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值