题目:
写一个完整的程序,实现随机生成20个元素的链表,快速查找中间结点的值并显示
代码:
#include<iostream>
#include<stdlib.h>
#include<ctime>
using namespace std;
typedef int ElemType;
struct Node
{
Node* next;
ElemType data;
};
typedef Node LinkList;
Node* Creat()//尾插法创建单链表
{
Node *head,*p,*q;
head=new Node;
head->next=NULL;
q=head;
srand((unsigned)time(NULL));
for(int i=0;i<20;i++)
{
p=new Node;
p->data=rand()%100+1;
q->next=p;
q=p;
}
p->next=NULL;
return head;
}
//返回一个未知大小的单链表的中间节点数据
ElemType GetMidNode(LinkList *L,ElemType *e)//快慢指针找到中间节点
{
LinkList *search,*mid;
mid=search=L;
while(search->next!=NULL)
{
if(search->next->next)//search是快指针,比慢指针mid运动速度快一倍
{
search=search->next->next;
mid=mid->next;
}
else
search=search->next;
}
*e=mid->data;
return *e;
}
void main()
{
LinkList *L=Creat();
LinkList *p=L->next;
for(int i=0;i<20;i++)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
int m=0;
int mid=GetMidNode(L,&m);
cout<<"中间节点数据是:"<<mid<<endl;
}
打印结果: