typedef int ElemType; struct sNode { ElemType data; sNode *next; }; sNode* FindListMiddleNode(sNode* HL)//带表头附加结点 { if(!HL || !HL->next)//如果HL为空或者它根本没有数据结点,返回NULL return NULL; sNode *pSlow, *pFast; pSlow = HL->next; pFast = HL->next->next; while(pFast && pFast->next) { pSlow = pSlow->next; pFast = pFast->next->next;//一次两步 } return pSlow;//返回中点 }
#include <iostream> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(nullptr){} }; ListNode* ListMedian(ListNode* head){ if(head == nullptr){ return nullptr; }//if ListNode *slow = head; ListNode *fast = head; while(fast->next != nullptr && fast->next->next != nullptr){ slow = slow->next; fast = fast->next->next; }//while return slow; } int main(){ int num[] = {1,2,3,4,5}; ListNode *head = new ListNode(0); ListNode *p = head,*node; for(int i = 0;i < 5;++i){ node = new ListNode(num[i]); p->next = node; p = p->next; }//for node = ListMedian(head->next); if(node != nullptr){ cout<<node->val<<endl; }//if }