/**************************************************** ********************
P54 Practice Question 1: Store the information of several cities in a singly linked list with a leading node. The city
information in the node includes the city name, the city's Position coordinates. Requirements:
(1) Given a city name, return its location coordinates;
(2) Given a location coordinate P and a distance D, return all cities whose distances from P are less than or equal to D.
**************************************************** *****************/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct
{
char CityName[10];
int x ,y;
}CityInfo;
typedef struct node
{
CityInfo data;
struct node *next;
}Node, *LinkList;
//Algorithm 2.5 Initialize the singly linked list with the head node
void InitList( LinkList *H)
{
*H = (LinkList)malloc (sizeof(Node));
(*H)->next = NULL;
}
//Output the elements of the linear list
void Print(LinkList H)
{
H = H->next;
while(H)
{
printf("City: %s\t Location: (%d,%d)\n",H- >data.CityName,H->data.x,H->data.y);
H = H->next;
}
printf("\n");
}
//Algorithm 2.10 Insert the singly linked list with the head node into
int InsList (LinkList L , int i, CityInfo e)
{//Insert the new element e at the i-th position in the linked list
Node *pre=L, *s;
int k= 0;
while(pre!=NULL&&k<i-1)
{ pre = pre->next;
k=k+1;
}
if( k != i-1 ) //The insertion position is unreasonable and return 0
return 0;
s = (Node *) malloc (sizeof (Node) ); //Create a new node
s->data = e;
s->next = pre->next; //Link in
pre->next = s;
return 1;
}
LinkList SearchCity(LinkList L, char c)
{
while(L->next && L->next->data.CityName[0]!=c)
L = L->next;
return L->next;
}
void main()
{
LinkList L, p;
struct tm t;
char c = 'A', str[20];
CityInfo e;
int i, x, y, d, xz;
_getsystime(&t);
srand(t.tm_sec );
InitList(&L);
for(i=0; i<10; i++)
{
e.CityName[0] = c+i;
e.CityName[1] = '\0';
ex = rand()%100 - 50;
ey = rand()%100 - 50;
InsList(L, i+1, e);
}
while(1)
{
Print(L);
printf("Choose the following operations: 1. Check the coordinates of the city name, 2 , Coordinate distance to check the city, 0, exit: ");
scanf("%d", &xz);
getchar();
switch(xz)
{
case 1:
printf("Find the coordinates according to the city name, please enter the city name: " );
gets(str);
p = SearchCity(L, str[0]);
if(p)
printf("City: %s\tLocation: (%d,%d)\n\n",p->data.CityName,p-> data.x,p->data.y);
else
printf("There is no such city!\n\n");
break;
case 2:
printf("Please enter the coordinates and distance:");
scanf("%d% d%d",&x,&y,&d);
p = L->next;
printf("The distance coordinates (%d,%d) are within the range of %d: ",x,y,d);
while (p)
{
if((p->data.xx)*(p->data.xx)+(p->data.yy)*(p->data.yy)<=d*d)
printf(" %s\t",p->data.CityName);
p = p->next;
}
printf("\n");
break;
case 0:
exit(0);
}
}
}