解析:设立两个指针,p每次移动两下,q每次只移动一下,那么当p指向最后一个节点的时候,那么q就是中间的节点了
ListNode* FindMidNode(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
if (pHead->m_pNext == NULL || pHead->m_pNext->m_pNext == NULL)
{
return pHead;
}
ListNode* pFirstNode = pHead;
ListNode* pSecondNode = pHead;
while(pFirstNode->m_pNext!= NULL && pFirstNode->m_pNext->m_pNext != NULL)//如果链表结点数为偶数,输出中间两个结点前面的一个。
{
pFirstNode = pFirstNode->m_pNext->m_pNext;
pSecondNode = pSecondNode->m_pNext;
}
return pSecondNode;
}
完整测试代码:
// FindMidNodeList.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
ListNode(int k): m_nValue(k),m_pNext(NULL)
{
}
};
ListNode* FindMidNode(ListNode* pHead)
{
if (pHead == NULL)
{
return NULL;
}
if (pHead->m_pNext == NULL || pHead->m_pNext->m_pNext == NULL)
{
return pHead;
}
ListNode* pFirstNode = pHead;
ListNode* pSecondNode = pHead;
while(pFirstNode->m_pNext!= NULL && pFirstNode->m_pNext->m_pNext != NULL)//如果链表结点数为偶数,输出中间两个结点前面的一个。
{
pFirstNode = pFirstNode->m_pNext->m_pNext;
pSecondNode = pSecondNode->m_pNext;
}
return pSecondNode;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode* head = new ListNode(1);
ListNode* Node1 = new ListNode(2);
ListNode* Node2 = new ListNode(3);
ListNode* Node3 = new ListNode(4);
ListNode* Node4 = new ListNode(5);
ListNode* Node5 = new ListNode(6);
ListNode* Node6 = new ListNode(7);
head->m_pNext = Node1;
Node1->m_pNext = Node2;
Node2->m_pNext = Node3;
Node3->m_pNext = Node4;
Node4->m_pNext = Node5;
Node5->m_pNext = NULL;
//Node6->m_pNext = NULL;
ListNode* p = FindMidNode(head);
cout<<p->m_nValue<<endl;
getchar();
return 0;
}