哈希表1

#include <string.h>  /* strcpy */  
#include <stdlib.h>  /* malloc */  
#include <stdio.h>   /* printf */  
#include "uthash.h"  

#define MAX_USERNAME_LEN      (30)
#define MAX_PHONENUM_LEN      (30)
#define ERROR_PARAMETER       (-1)
#define ERROR_USER_EXISTS     (-2)
#define ERROR_USER_NOT_EXISTS (-3)
#define SUCCESS               (0)

typedef struct UserAndPhone
{
    char userName[MAX_USERNAME_LEN];
    char phoneNumber[MAX_PHONENUM_LEN]; 
}UserAndPhone;

typedef struct PhoneBook 
{  
    char userName[MAX_USERNAME_LEN];      /* key */  
    char phoneNumber[MAX_PHONENUM_LEN];  
    UT_hash_handle hh;                    /* makes this structure hashable */  
}PhoneBook;  

PhoneBook* users = NULL;                  /* 用戶及電話的哈希表 */
UserAndPhone* userAndPhone = NULL;        /* 存放遍歷的用戶及電話 */
int userCnt = 0;                          /* 存放用戶數 */

/*******************************************************************
****功    能:將新的用戶、電話號碼插入到哈希表
****輸入參數:phoneBook存放用戶名、電話號碼和哈希句柄,該參數由用戶動態申請內存
****返 回 值:-1參數錯誤,-2用戶已存在、0添加成功
*******************************************************************/
int InsertUserAndPhone(PhoneBook* phoneBook)
{
    if ((NULL == phoneBook)
     || (NULL == phoneBook->userName)
     || (NULL == phoneBook->phoneNumber)
     || (0 == strlen(phoneBook->userName))
     || (0 == strlen(phoneBook->phoneNumber)))
    {
        printf("error parameter.\n");
        return ERROR_PARAMETER;
    }
    
    PhoneBook* tmp;
    HASH_FIND_STR(users, phoneBook->userName, tmp);

    if (NULL != tmp)
    {
        printf("the userName[%s] already exist.\n", phoneBook->userName);
        return ERROR_USER_EXISTS;
    }
    
    HASH_ADD_KEYPTR(hh, users, phoneBook->userName, strlen(phoneBook->userName), phoneBook);  

    ++userCnt;

    return SUCCESS;
}

/****************************************************************************************
******功    能:根據用戶名查找電話號碼
******輸入參數:userName表示要查詢的用戶名
******          phoneNumberFound 用來存放查找到的電話號碼(由調用者保證空間足夠大)
******返 回 值:-1參數錯誤,-3用戶不存在,0找到
*****************************************************************************************/
int findPhoneNumber(char* userName, char *phoneNumberFound)
{
    if ((NULL == userName) 
    || (0 == strlen(userName))
    || (NULL == phoneNumberFound))
    {
        printf("invalid parameter.\n");
        return ERROR_PARAMETER;
    }
    
    PhoneBook* tmp;
    HASH_FIND_STR(users, userName, tmp);
    
    if (NULL == tmp)
    {
        printf("the userName[%s] does not exist.\n", userName);
        return ERROR_USER_NOT_EXISTS;
    }
    else
    {    
        strcpy(phoneNumberFound, tmp->phoneNumber);
        
        return SUCCESS;
    }
    

}
相關文章
相關標籤/搜索