给出一个单链表,不知道N的值,怎样遍历一次就可以求出中间结点

书上的思路是设立两个指针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;
}

结果图

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值