1396. 设计地铁系统
C代码:哈希表运用
typedef struct {
int id;
char* stationIn;
int timeIn;
char* stationOut;
int timeOut;
UT_hash_handle hh;
} UndergroundSystem;
UndergroundSystem* head = NULL;
UndergroundSystem* undergroundSystemCreate() {
return NULL;
}
void undergroundSystemCheckIn(UndergroundSystem* obj, int id, char * stationName, int t) {
UndergroundSystem* out = NULL;
HASH_FIND_INT(head, &id, out);
if (NULL == out) {
out = (UndergroundSystem*)malloc(sizeof(UndergroundSystem));
out->id = id;
out->stationIn = stationName;
out->timeIn = t;
out->stationOut = "";
out->timeOut = 0;
HASH_ADD_INT(head, id, out);
}
}
void undergroundSystemCheckOut(UndergroundSystem* obj, int id, char * stationName, int t) {
UndergroundSystem* out = NULL;
HASH_FIND_INT(head, &id, out);
if (NULL != out) {
out->stationOut = stationName;
out->timeOut = t;
out->id = 0;
}
}
double undergroundSystemGetAverageTime(UndergroundSystem* obj, char * startStation, char * endStation) {
UndergroundSystem* cur = NULL;
UndergroundSystem* next = NULL;
int sum = 0;
int cnt = 0;
HASH_ITER(hh, head, cur, next) {
if ((strcmp(cur->stationIn, startStation) == 0) && (strcmp(cur->stationOut, endStation) == 0)) {
sum += (cur->timeOut - cur->timeIn);
cnt++;
}
}
return sum / (double)cnt;
}
void undergroundSystemFree(UndergroundSystem* obj) {
HASH_CLEAR(hh, head);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)