快慢指针是指设计两个指针,p1,p2,p1一次往后移1,p2往后移2(比1大),即p2指针始终比p1走得快,当p2走到末尾,为空时,p1即为链表中间节点,当结点为偶数时,中间结点为中间两个结点的前一个
#include<iostream>
using namespace std;
typedef struct stu
{
int num;
stu* next;
}node,*nodelist;
nodelist creat_list(nodelist L)
{
int n;
cout<<"请输入要添加的学生人数"<<endl;
cin>>n;
while(n--)
{
nodelist p=new node;
p->num=n;
p->next=L;
L=p;
}
return L;
}
void display(nodelist L)
{
nodelist p;
for(p=L;p!=NULL;p=p->next)
{
cout<<p->num<<" ";
}
}
void output_result(nodelist L)
{
nodelist p1,p2;
p1=p2=L;
while(p2!=NULL && p2->next!=NULL)
{
p1=p1->next;
p2=p2->next->next;
}
cout<<"中间的数为"<<p1->num<<endl;
}
int main()
{
nodelist L=NULL;
L=creat_list(L);
display(L);
output_result(L);
while(L)
{
nodelist temp=L;
L=L->next;
delete temp;
}
return 0;
}