#include
#include
#include
#include
#include
#include
/*
将若干个城市的信息存入一个带头结点的单链表,
结点中的城市信息包括城市名、城市的位置坐标。
要求:
(1)给定一个城市名,返回其位置坐标;
(2)给定一个位置坐标P和一个距离D,返回所有与P的距离小于等于D的城市。
*/
//坐标结构体
struct Point
{
double X;//X坐标
double Y;//Y坐标
};
//城市结构体
struct City
{
char Name[100];//城市名称
Point Ps;//该城市的坐标
City *pNext;//下个结点
};
//计算a,b两个坐标点之间的距离
double ComputeDistance(Point a,Point b)
{
return sqrt( pow((a.X - b.X),2) + pow((a.Y - b.Y),2) );
}
void main(void)
{
City *pHead = NULL;
City *pWork = NULL;
int i = 0;
char tmpInput[1024];
srand(time(NULL));
//随机生成几个城市的结点
for ( i = 0 ; i < 10 ; i++ )
{
City *tmpNode = new City();
sprintf(tmpNode->Name,"城市%d",i+1);
tmpNode->Ps.X = rand();
tmpNode->Ps.Y = rand();
tmpNode->pNext = NULL;
if ( pHead == NULL )
{
pHead = tmpNode;
pWork = pHead;
}
else
{
pWork->pNext = tmpNode;
pWork = pWork->pNext;
}
}
//输出所有城市列表
pWork = pHead;
while ( NULL != pWork )
{
printf("城市 : 名称=%s 坐标: X = %f Y =%f\n",pWork->Name,pWork->Ps.X,pWork->Ps.Y);
pWork = pWork->pNext;
}
printf("输入城市名(如: 城市1) = ");
memset(tmpInput,0x0,sizeof(tmpInput));
scanf("%s",tmpInput);
//查找城市
pWork = pHead;
while ( NULL != pWork )
{
if ( strcmp(pWork->Name,tmpInput) == 0 )
{
printf("找到城市 : 名称=%s 坐标: X = %.2f Y =%.2f\n",pWork->Name,pWork->Ps.X,pWork->Ps.Y);
break;
}
pWork = pWork->pNext;
}
//判断距离小于D的城市
Point P;
double D = 0.0;
memset(tmpInput,0x0,sizeof(tmpInput));
printf("输入一个位置 X坐标 = ");
scanf("%s",tmpInput);
P.X = atof(tmpInput);
printf("输入一个位置 Y坐标 = ");
scanf("%s",tmpInput);
P.Y = atof(tmpInput);
printf("输入一个判断距离 = ");
scanf("%s",tmpInput);
D = atof(tmpInput);
//循环判断并输出
pWork = pHead;
while ( NULL != pWork )
{
if ( ComputeDistance(pWork->Ps,P) < D )
{
printf("找到到点(%f,%f)距离小于%f的城市 :\n\t名称=%s 坐标: X = %.2f Y =%.2f\n",P.X,P.Y,D,pWork->Name,pWork->Ps.X,pWork->Ps.Y);
}
pWork = pWork->pNext;
}
//释放链表
pWork = pHead;
City *pWorkNext = pWork->pNext;
while ( NULL != pWork )
{
delete pWork;
pWork = pWorkNext;
if ( pWork != NULL )
{
pWorkNext = pWork->pNext;
}
}
fflush(stdin);
getchar();
}