数据结构——链表实现通讯录

本文通过上文实现的链表,实现一个简单的通信录

通讯录功能:

  1. 添加联系人
  1. 查找联系人
  2. 删除联系人
  3. 显示所有联系人

(1)定义联系人信息结构

typedef struct {
    char key[15]; //名字
    char addr[20];
    char telephone[15];
    char mobile[12];
    //可根据需要增加QQ、E-mail等
} DATA;

(2)显示联系人模块

void ChainListAll(ChainListType *head)
{
    ChainListType *h;
    DATA data;
    h = head;
    int i = 0;

    printf("通信录所有联系人如下:\n");

    while (h) {
        //data = h->data;
        printf("联系人%d ", ++i);
        printf("姓名:%s ", h->data.key);
        printf("地址:%s ", h->data.addr);
        printf("电话:%s ", h->data.telephone);
        printf("手机:%s\n", h->data.mobile);
        h = h->next;
    }
    return;
}

(3)添加联系人模块

ChainListType *input(ChainListType *head)
{
    DATA data;
    printf("请输入联系人信息\n");
    printf("姓名:");
    scanf("%s", data.key);
    printf("地址:");
    scanf("%s", data.addr);
    printf("电话:");
    scanf("%s", data.telephone);
    printf("手机:");
    scanf("%s", data.mobile);

    return ChainListAddFirst(head, data);
}

(4)查找联系人模块

void find(ChainListType *head)
{
    ChainListType *h;
    DATA data;
    char name[15];

    printf("请输入查找姓名:");
    scanf("%s", name);
    h = ChainListFind(head, name);
    if (h) {
        data = h->data;
        printf("姓名:%s ", data.key);
        printf("地址:%s ", data.addr);
        printf("电话:%s ", data.telephone);
        printf("手机:%s ", data.mobile);
    } else {
        printf("未找到姓名为%s的联系人\n", name);
    }
}

(5)删除联系人模块

void delete(ChainListType *head)
{
    ChainListType *h = head;
    char name[15];
    int result = 0;

    printf("请输入要删除的姓名:");
    scanf("%s", name);

    result = ChainListDelete(head, name);
    if (result) {
        printf("删除成功!\n");
    } else {
        printf("删除失败!\n");
    }
}

(6)主函数模块

int main()
{
    ChainListType *head = NULL;
    int select;
    do {
        printf("\n________________________\n");
        printf("1.添加联系人\n");
        printf("2.查找联系人\n");
        printf("3.删除联系人\n");
        printf("4.显示所有联系人\n");
        printf("0.退出\n");
        scanf("%d", &select);
        switch (select) {
            case 1:
                printf("添加联系人\n");
                head = input(head);
                break;
            case 2:
                printf("查找联系人\n");
                find(head);
                break;
            case 3:
                printf("删除联系人\n");
                delete(head);
                break;
            case 4:
                printf("显示联系人\n");
                ChainListAll(head);
                break;
            case 0:
                return 0;
        }
    } while(1);

    return 0;
}

注:有兴趣的同学可以,结合MFC或者QT实现一个图形界面

推荐阅读更多精彩内容