/*
本实验证明:遇到问题,当遍历链表的时候,没有用p=p->next;的时候,会打印7次,加上这一行的话,可以正常的把中间节点的值找到。
*/
#include <stdio.h>
#include <stdlib.h>
#define ERROR 1
#define SUCCESS 0
typedef struct _node{
int data;
struct _node *next;
}node;
node *gpNode=NULL;
node* CreateNode(node *p){
node*temp=(node*)malloc(sizeof(node));
if(temp==NULL){
printf("malloc fail\n");
}
temp->next=NULL;
return temp;
}
node* AddNode(node *p,int e){
p->data=e;
p->next=NULL;
node*temp=(node*)malloc(sizeof(node));
if(temp==NULL){
printf("malloc fail\n");
}
temp->next=NULL;
p->next=temp;
p=p->next;
return p;
}
/*
该函数传递参数有一个条件,传入的链表的指针必须指向第一个节点
*/
void FindMidNode(node *p,int *e){
int count=1;
node *pFast = NULL;
node *pSlow = NULL;
pFast=p;
pSlow=p;
while(p->next!=NULL){
p=p->next;
printf("pFast data value is:%d\n",pFast->data);
pFast=pFast->next;
if(count%2==0){
pSlow=pSlow->next;
printf("pSlow data value is:%d\n",pSlow->data);
}
count++;
printf("e value is:\n");
}
*e=pSlow->data;
}
int main(){
node *pNode=NULL;
node *pCount= NULL;
pNode=CreateNode(gpNode);
pCount=pNode;
pNode=AddNode(pNode,3);
pNode=AddNode(pNode,4);
pNode=AddNode(pNode,5);
pNode=AddNode(pNode,6);
pNode=AddNode(pNode,7);
pNode=AddNode(pNode,8);
int buf=0;
FindMidNode(pCount,&buf);
//printf("FindMidNode end:\n");
printf("mid value is:%d\n",buf);
return 0;
}
运行结果
pFast data value is:3
e value is:
pFast data value is:4
pSlow data value is:4
e value is:
pFast data value is:5
e value is:
pFast data value is:6
pSlow data value is:5
e value is:
pFast data value is:7
e value is:
pFast data value is:8
pSlow data value is:6
e value is:
mid value is:6