查找单项链表中间元素,若有相同,取第一个
#include <stdio.h>
#include <stdlib.h> typedef struct Lnode{ int data; struct Lnode *next; }Lnode, *LinkList; //创建一个起始元素为start,终止元素为end的链表 Lnode *CreateList_L(int start, int end){ Lnode *L, *p, *rear; int i; L = (LinkList) malloc(sizeof(Lnode)); L->next = NULL; //尾插法 rear = L; for(i = start; i <= end; i++){ p = (LinkList) malloc(sizeof(Lnode)); p->data = i; rear->next = p; rear = p; } rear->next = NULL; return L; } Lnode *FindMid_L(Lnode *L){ Lnode *pSlow, *pFast; pSlow = pFast = L; //必须判断pFast 和pFast->next,因为当pFast指向链表最后一个元素时, //不判断pFast->next,则执行循环语句pFast->next->next内存溢出 while(pFast && pFast->next){ pSlow = pSlow->next; pFast = pFast->next->next; } return pSlow; } main() { Lnode *L, *p; //创建链表 L = CreateList_L(1, 101); p = FindMid_L(L); printf("%d\n",p->data); }