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

来源:互联网 发布:国外创意广告视频 知乎 编辑:程序博客网 时间:2024/06/06 17:23

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

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 )//坑1pHead->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;}


原创粉丝点击