ListNode* MidNode( ListNode* pHead )
{
if ( NULL == pHead )
return NULL;
else if ( NULL == pHead->m_pNext )
return pHead;
else if ( NULL == pHead->m_pNext->m_pNext )
return pHead;
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
while ( NULL != pFast->m_pNext/*最后一个结点*/ ){
if ( NULL == pFast->m_pNext->m_pNext )//pFast->m_pNext不可能为NULL. 所以我们不必担心NULL->m_pNext情况发生
break;
pFast = pFast->m_pNext->m_pNext;
pSlow = pSlow->m_pNext;
}
return pSlow;
}
测试代码:
//求链表的中间节点,链表中元素个数为奇数返回中间节点,偶数返回中间结点中任一个(这里返回第一个)
#include <iostream>
using namespace std;
struct ListNode{
int m_nKey;
ListNode* m_pNext;
ListNode( ListNode* pNext, int value )
: m_pNext( pNext )
, m_nKey( value )
{}
};
ListNode* MidNode( Li