书上的思路是设立两个指针p和q,p每次移动一个位置,q每次移动2个位置,当q到达最后一个结点时,p指向的是中间结点。
试着运行了下书上的程序,发现运行出错,认真的看了下,发现有个错误。
while(head->next->next!=NULL)
这里不能保证head->next不为空,如果head->next==NULL时,那么上面这句就会出错了。
我试着将它的程序进行了改动,即在上面加上head->next!=NULL。
全部代码如下:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<conio.h>
using namespace std;
typedef struct student
{
int data;
struct student *next;
}node;
node *create() //创建单链表
{
node *head,*p,*s;
int x,cycle=1;
head=(node *)malloc(sizeof(node));
p=head;
printf(" please input the data:\n");
while(cycle)
{
scanf("%d",&x);
if(x!=0)
{
s=(node *)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
}
else
{
cycle=0;
}
}
head=head->next;
p->next=NULL;
return(head);
}
void print(node *head) //打印单链表
{
node *p;
int n;
p=head;
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
node *searchmid(node *head) //查找单链表的中间结点
{
node *p,*q,*mid;
p=head;
q=head;
while(q->next&&q->next->next!=NULL)//改动部分:保证q->next不为空
{
q=q->next->next;
p=p->next;
mid=p;
}
return mid;
}
int main()
{
node *head,*mid;
int len;
head=create();
printf("these records are: \n");
print(head);
mid=searchmid(head);
printf("中间结点为:%d\n",mid->data);
return 0;
}