利用快慢指针原理:设置两个指针search、mid都指向单链表的头节点。其中 search的移动速度是mid的2倍。当*search指向末尾节点的时候,mid正好就在中间了。这也是标尺的思想。
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef Node *LinkList;
void GetElem(LinkList head);
void CreateList(LinkList *head);
void PrintList(LinkList head);
int main(void)
{
LinkList head;
CreateList(&head);
PrintList(head);
GetElem(head);
system("pause");
return 0;
}
void CreateList(LinkList *head)
{
*head = (Node *)malloc(sizeof(Node));
(*head)->next=NULL;
Node *tail,*s;
tail = *head;
int num;
cout<<"请输入你要创立的节点个数";
cin>>num;
for(int i=0;i<num;i++)
{
s=(Node *)malloc(sizeof(Node));
s->data=i+1;
tail->next=s;
tail=s;
}
tail->next=NULL;
}
void GetElem(LinkList head)
{
Node *fast=head,*low=head;
while(fast->next!=NULL)
{
if(fast->next->next)
{
fast=fast->next->next;
low=low->next;
}
else
{
fast=fast->next;low=low->next;
}
}
cout<<"中间值为:"<<low->data<<endl;
}
void PrintList(LinkList head)
{
Node *p;
for(p=head->next;p;p=p->next)
{
cout<<p->data<<endl;
}
}