Добавил:
alex20000
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:sem10_2
.c#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_SIZE 512
struct city
{
char* name;
unsigned population;
};
typedef struct city* city_pointer;
typedef struct table_elem* table_pointer;
struct table_elem
{
city_pointer city;
table_pointer next;
};
int get_option();
unsigned hash(char* name);
void add_city(char* name, unsigned population);
void print_cities();
void remove_city(char* name);
table_pointer table[HASH_SIZE];
int main()
{
for(int i = 0; i != HASH_SIZE; ++i)
table[i] = NULL;
for(;;)
{
switch(get_option())
{
case 1:
{
printf("Input city name:");
char name[128];
scanf("%s", name);
printf("Input city population:");
int ppl;
scanf("%d", &ppl);
add_city(name, ppl);
}
break;
case 2:
{
printf("Input city name:");
char name[128];
scanf("%s", name);
remove_city(name);
}
break;
case 3:
print_cities();
break;
};
}
}
int get_option()
{
puts("1. Add city");
puts("2. Remove city");
puts("3. List cities");
int option;
scanf("%d", &option);
return option;
}
unsigned hash(char* name)
{
unsigned result = 0;
for(;*name != '\0'; ++name)
{
result = *name + result * 31;
}
return result % HASH_SIZE;
}
void add_city(char* name, unsigned population)
{
unsigned h = hash(name);
table_pointer curr = table[h];
if(table[h] == NULL)
{
table[h] = (table_pointer)malloc(sizeof(struct table_elem));
curr = table[h];
}
else
{
while(curr->next != NULL)
curr = curr->next;
curr = (table_pointer)malloc(sizeof(struct table_elem));
}
curr->city = (city_pointer)malloc(sizeof(struct city));
curr->city->name = (char*)malloc(strlen(name));
strcpy(curr->city->name, name);
curr->city->population = population;
curr->next = NULL;
}
void print_cities()
{
for(int i = 0; i != HASH_SIZE; ++i)
{
table_pointer curr = table[i];
while(curr != NULL)
{
printf("%s -- Population: %d\n", curr->city->name, curr->city->population);
curr = curr->next;
}
}
}
void remove_city(char* name)
{
unsigned h = hash(name);
table_pointer prev = NULL;
table_pointer curr = table[h];
if(curr == NULL)
{
puts("This city does not exist!!");
return;
}
do
{
//printf("|%s|%s|", curr->city->name, name);
if(!strcmp(curr->city->name, name))
{
if(prev == NULL)
{
table[h] = curr->next;
}
else
{
prev->next = curr->next;
}
free(curr->city->name);
free(curr->city);
puts("This city is successfully removed!");
return;
}
prev = curr;
curr = curr->next;
}while(curr->next != NULL);
puts("This city does not exist!");
return;
}
Соседние файлы в предмете Информатика