C + + algorithm for finding the middle node of a linked list

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.