// FindMidPoint.cpp : Defines the entry point for the console application. //要寻找一个单链表的中间节点 //(1) 使用两个指针进行遍历,快指针每次步进2,慢指针每次步进1; //(2) 当快指针到达链表尾部的时候,慢指针指向的就是链表的中点。 #include "stdafx.h" #include <malloc.h> #include <assert.h> typedef struct node Node; struct node{ int value; Node* next; }; Node* initData(int start,int end){ Node *head=(Node*)malloc(sizeof(Node)); Node *p=head; int i=0; for(i=start;i<=end;i++){ Node *node=(Node*)malloc(sizeof(Node)); node->value=i; p->next=node; p=node; } head=head->next; p->next=NULL; return head; } void dump(Node *head){ assert(head!=NULL); while (head!=NULL) { printf("%d/t",head->value); head=head->next; } } Node* findMidElement(Node *head){ assert(head!=NULL); Node* mid=head; Node* p=mid->next; while(NULL!=p && NULL!=p->next){ mid=mid->next; p=p->next->next; } return mid; } int main(int argc, char* argv[]) { Node *linkList=initData(2,17); dump(linkList); node* mid=findMidElement(linkList); if (mid!=NULL) { printf("/n%d/n",mid->value); } return 0; }