Resolution: Set up two pointers, p each move twice, Q only move a bit at a time, then when P points to the last node, then Q is the middle node
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)//If the list node number is even, the output is one of the first two nodes in the middle. {Pfirstnode = Pfirstnode->m_pnext->m_pnext;psecondnode = Psecondnode->m_pnext;} return psecondnode;}
Complete test Code:
FindMidNodeList.cpp: Defines the entry point of the console application. #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)//If the list node number is even, the output is one of the first two nodes in the middle. {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;}
C + + algorithm for finding the middle node of a linked list