写的还是很坑的,今天状态奇差
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;
}