找到链表中间一个节点值

/*
本实验证明:遇到问题,当遍历链表的时候,没有用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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值