输出一个单向链表中间的结点

来源:互联网 发布:ios开发中数据库fmdb 编辑:程序博客网 时间:2024/05/19 12:26
扩展:输入一个单向链表。如果该链表的结点数为奇数,输出中间的结点;如果链表结点数为偶数,输出中间两个结点前面的一个。

思路一:先遍历一遍链表,获得链表节点总数,再根据总节点数的奇偶性输出中间节点。

思路二:两个指针,一快一慢,慢指针每走一步,快指针走两步。当快指针指向节点的下一节点或下一节点的下一节点为空时,慢指针所指即是中间节点。

//coder:LEE

//20120310
#include<iostream>
#include<cassert>
using namespace std;
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
void CreateListNode(ListNode *pHead)
{
for (int i=3;i<7;i++)
{
ListNode *pCur=new ListNode();
pCur->m_nKey=i;
pCur->m_pNext=NULL;
pHead->m_pNext=pCur;
pHead=pCur;
}
}
void DisplayListNode(ListNode *pHead)
{
while (pHead)
{
cout<<pHead->m_nKey<<" ";
pHead=pHead->m_pNext;
}
cout<<endl;


}
ListNode *OutputMidNode(ListNode *pHead)
{
assert(pHead!=NULL);

ListNode *pFast=pHead;
ListNode *pSlow=pHead;
while (pFast->m_pNext&&pFast->m_pNext->m_pNext)
{
pFast=pFast->m_pNext->m_pNext;
pSlow=pSlow->m_pNext;
}
return pSlow;


}


int main()
{
ListNode *pHead=new ListNode();
pHead->m_nKey=0;
pHead->m_pNext=NULL;
CreateListNode(pHead);
DisplayListNode(pHead);
cout<<OutputMidNode(pHead)->m_nKey<<endl;
return 0;
}