c/c++双向链表+哈希表实现简易通讯录

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NAMA_LENGTH 30
#define PHONE_LENGTH 20
#define TABLE_SIZE 26  //假设只有英文字母
#pragma warning(disable:4996)
//按照姓名首字母存储通讯录,使用哈希数组+双向链表

//定义联系人列表的结构
typedef struct People {
    char name[NAMA_LENGTH];
    char phone[PHONE_LENGTH];
    struct People* prev;
    struct People* next;
} People;

//使用哈希表定义联系人列表的结构
typedef struct ContactsList {
    People* head[TABLE_SIZE]; // Each entry is the head of a linked list 每个条目都是链表的头部
} ContactsList;

// 用于在链表中插入和删除节点的宏
#define LIST_INSERT(item, list) do{\
    item->next = list;\
    item->prev = NULL;\
    if (list != NULL) list->prev = item;\
    (list) = item;\
}while(0)

#define LIST_REMOVE(item, list) do{\
    if (item->prev != NULL) item->prev->next = item->next;\
    if (item->next != NULL) item->next->prev = item->prev;\
    if (list == item) list = item->next;\
    item->prev = NULL;\
    item->next = NULL;\
}while(0)


//将名称的第一个字母转换为索引的哈希函数
int hashFunction(const char* name) {
    return toupper(name[0]) - 'A';//小写转换成大写字母
}

//将联系人插入哈希表的函数
void insertContact(ContactsList* clist, const char* name, const char* phone) {
    int index = hashFunction(name);
    People* newPerson = (People*)malloc(sizeof(People));
    strcpy(newPerson->name, name);
    strcpy(newPerson->phone, phone);
    LIST_INSERT(newPerson, clist->head[index]);
}

// 从哈希表中删除联系人的函数
void removeContact(ContactsList* clist, const char* name) {
    int index = hashFunction(name);
    People* current = clist->head[index];
    while (current != NULL) {
        if (!strcmp(current->name, name)) {
            LIST_REMOVE(current, clist->head[index]);
            free(current); //删除后释放内存
            break;
        }
        current = current->next;
    }
}

//打印所有触点进行调试的功能
void printContacts(ContactsList* clist) {
    for (int i = 0; i < TABLE_SIZE; ++i) {
        People* current = clist->head[i];
        while (current != NULL) {
            printf("Name: %s, Phone: %s\n", current->name, current->phone);
            current = current->next;
        }
    }
}

int main() {
    ContactsList clist;
    //初始化所有指针为NULL
    memset(clist.head, 0, sizeof(clist.head)); 

    insertContact(&clist, "John Doe", "123-456-7890");
    insertContact(&clist, "Dane Doe", "987-654-3210");
    insertContact(&clist, "Acam Smith", "111-222-3333");
    printContacts(&clist);


    removeContact(&clist, "John Doe");
    printf("\n\n\n");

    printContacts(&clist);

    return 0;
}

数据结构简图:

链表数据结构:


哈希数据结构:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值