每日一题(8) - 求链表的中间结点

来源:互联网 发布:北京租房软件 编辑:程序博客网 时间:2024/06/03 16:52

题目来自剑指Offer

题目


分析


代码

ListNode* FindMidNode(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;}

测试代码

#include <iostream>#include <assert.h>using namespace std;struct ListNode{int m_Data;ListNode* m_pNext;};ListNode* FindMidNode(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;}void CreateList(ListNode** pHead,int nLen)//头指针使用指针的指针{assert(*pHead == NULL && nLen > 0);ListNode* pCur = NULL;ListNode* pNewNode = NULL;for (int i = 0;i < nLen;i++){pNewNode = new ListNode;cin>>pNewNode->m_Data;pNewNode->m_pNext = NULL;if (*pHead == NULL){*pHead = pNewNode;pCur = *pHead;}else{pCur->m_pNext = pNewNode;pCur = pNewNode;}}}void PrintList(ListNode* pCurNode){assert(pCurNode != NULL);  while (pCurNode)  {  cout<<pCurNode->m_Data<<" ";  pCurNode = pCurNode->m_pNext;  }  cout<<endl;}int main(){int nLen = 0;ListNode* pHead = NULL;ListNode* pMidNode = NULL;cout<<"please input node num: ";cin >> nLen;CreateList(&pHead,nLen);//注意传参使用引用PrintList(pHead);pMidNode = FindMidNode(pHead);cout<<"MidNode: "<<pMidNode->m_Data<<endl;system("pause");return 1;}


原创粉丝点击