问题:
找出单链表的中间元素
思路:
快慢指针。
快指针每次走两步,慢指针每次走1步。快指针走到头时,慢指针所指即为中间结点。
如果结点个数N为偶数,则中间结点为第N/2个结点。
// LinkTable.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//链表的结构体
struct node
{
char val;
node * next;
};
//2,找第4个结点
struct node * create( string & str_link )
{
int len = str_link.length();
struct node * phead = new node(); //带有表头的链表,表头中不存储任何元素
struct node * preNode = phead;
for( int i=0; i<len; i++ )
{
struct node * pNode = new node();
pNode->val = str_link[i];
pNode->next = NULL;
preNode->next = pNode;
preNode = pNode;
}
return phead;
}
void out_link( struct node * phead )
{
if( phead == NULL )
return;
struct node * pNode = phead->next;
while( pNode )
{
cout <<pNode->val;
pNode = pNode->next;
}
cout << endl;
}
struct node * find_mid_node( struct node * phead )
{
if( !phead ) return NULL;
//快慢指针
struct node *pFast = phead;
struct node *pSlow = phead;
int count = 1;
while(pFast)
{
pFast = pFast->next;
if( (count++)%2 ==0 )
pSlow = pSlow->next;
}
return pSlow;
}
void test()
{
string str;
cin >> str;
struct node *phead = create( str );
cout << "The Link is : ";
out_link( phead );
struct node *pNode = find_mid_node( phead );
if( pNode )
cout << "The mid node's value is : " << pNode->val <<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
return 0;
}