一个链表只遍历一次求出中间的节点
解析:设立两个指针,p每次移动两下,q每次只移动一下,那么当p指向最后一个节点的时候,那么q就是中间的节点了
代码:
// FindTheMidNode.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;struct Node{int data;Node* next;};Node* create_Link(int a[],int len){Node* head,*p,*q;p=new Node();p->data=a[0];head=p;for (int i=1;i<len;i++){q=new Node();q->data=a[i];p->next=q;p=q;}return head;}Node* findMid(Node* head){Node* pfast,*pslow;pfast=pslow=head;while (pfast->next && pfast->next->next){pfast=pfast->next->next;pslow=pslow->next;}return pslow;}int _tmain(int argc, _TCHAR* argv[]){int a[]={1,2,3,4,5,6,7};int len=sizeof(a)/sizeof(int);Node* head=create_Link(a,len);Node* mid=findMid(head);cout<<mid->data<<endl;system("pause");return 0;}