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

Posted ssopp24

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了不开辟新空间反转单链表(递归版本)相关的知识,希望对你有一定的参考价值。

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

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;


以上是关于不开辟新空间反转单链表(递归版本)的主要内容,如果未能解决你的问题,请参考以下文章

反转链表(在原链表进行操作,不开辟新空间. O(N)

理解单链表的反转(java实现)

合并两个排序的链表使之依然有序(不开辟新空间在原链表上操作的非递归版本)

单链表逆置

看图理解单链表的反转

递归-反转单链表 -图解