分析: 两个人赛跑,如果A速度是B的2倍,那么,当A到达终点的时候,B刚好到中间位置(这种思想很重要)
注:延伸:“删除单链表的中间元素”,道理相同,只要找出,删除该结点即可。
#include<cstdlib>
const int MaxSize = 101;
using namespace std;
typedef struct ListNode{
int data;
struct ListNode *next;
}ListNode;
void FindMidList(ListNode *L)
{
ListNode *p1;
ListNode *p2;
p1 = L;
p2 = L;
while(1)
{
if(p2->next != NULL&&p2->next->next != NULL)
{
p1 = p1->next;
p2 = p2->next;
}
else
{
break;
}
}
cout<<p1->data<<endl;
}
void Print(ListNode *L)
{
ListNode *p;
p = L->next;
while(p != NULL)
{
cout<<p->data<<endl;
p = p->next;
}
}
int main()
{
int num;
ListNode *A;
ListNode *r;
ListNode *s;
A = (ListNode*)malloc(sizeof(ListNode));
r = A;
while(cin>>num)
{
s = (ListNode*)malloc(sizeof(ListNode));
s->data = num;
r->next= s;
r = r->next;
}
r->next = NULL;
FindMidList(A);
//Print(A);
return 0;
}