/*
**节点值未知,只遍历单链表一次,求出中间节点
**函数参数为指向单链表首节点的指针
*/
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct NODE{
struct NODE* next;
int value;
}Node;
/*
**返回链表的中间节点值
*/
int middlePoint(Node **first)
{
Node *current,*p;
current = *first;
p = *first;
if(current == NULL)
{
printf("erro:null list!\n");
return FALSE;
}
else if(current->next == NULL)
return current->value;
else
current = current->next->next;
/*
**current右移的距离设为m,p右移的距离设为n
**则有:m = 2n 或 m = 2n+1.
*/
while(current)
{
p = p->next;
if(current->next != NULL)
current = current->next->next;
else
break;
}
return p->value;
}
/*
**测试用,在主函数里建一个无序链表,然后对其逆置
*/
int main(void)
{
Node *head,*newNode,*temp;
int newValue,middleValue,count = 8; //测试用的整数个数
head = NULL;
printf("请输入%d个整数:\n",count);
scanf("%d",&newValue);
head = (Node*)malloc(sizeof(Node));
head->value = newValue;
head->next = NULL;
temp = head;
while(--count)
{
scanf("%d",&newValue);
newNode = (Node*)malloc(sizeof(Node));
newNode->value = newValue;
newNode->next = NULL;
temp->next = newNode;
temp = newNode;
newNode = NULL;
}
temp->next=NULL;
middleValue = middlePoint(&head);
printf("链表的中间值为:%d\n",middleValue);
return TRUE;
}