双链表写通讯录
本人用双链表写的一个通讯录,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Contacts *head = NULL;
typedef struct Contacts
{
char name[100];
char number[100];
struct Contacts *pre;
struct Contacts *next;
}Contact;
void Initial(void)
{
head=(Contact*)malloc(sizeof(Contact));
if (head == NULL)
{
printf("创建失败\n");
exit(0);
}
memset(head->name,0,sizeof(head->name));
memset(head->number, 0, sizeof(head->number));
head->next = NULL;
head->pre = head->next;
printf("初始化成功\n");
}
void InsertList(Contact **Con)
{
if (*Con == NULL)
{
printf("请先初始化\n");
exit(0);
}
Contact *Newnode=(Contact *)malloc(sizeof(Contact));
printf("请输入新增联系人的名字:\n");
scanf_s("%s", Newnode->name,100);
printf("请输入新增联系人的电话号码:\n");
scanf_s("%s", Newnode->number,100);
if ((*Con)->next == NULL)
{
(*Con)->next = Newnode;
Newnode->next = NULL;
Newnode->pre = (*Con);
}
else {
Newnode->next = (*Con)->next;
(*Con)->next->pre=Newnode;
Newnode->pre = *Con;
(*Con)->next = Newnode;
}
printf("新建联系人成功\n");
}
void PritnList(Contact *Con)
{
if(Con == NULL || Con->next == NULL)
{
printf("是一个空表\n");
exit(0);
}
Con = (Con)->next;
while (Con != NULL)
{
printf("名字:%s ", (Con)->name);
printf("电话号码:%s\n", (Con)->number);
Con = (Con)->next;
}
}
void DelList(Contact **Con,char *str)
{
Contact *current = *Con;
while ((current)!=NULL&&(strcmp((current)->name,str))&& (strcmp((current)->number, str)))
{
current = current->next;
}
if (current != NULL)
{
if (!strcmp((current)->name, str)|| !strcmp((current)->number, str))
{
if (current->next != NULL)
{
current->pre->next = current->next;
current->next->pre = current->pre;
}
else {
current->pre->next = NULL;
}
}
else
{
printf("没有找到");
}
printf("删除成功\n");
}
}
void Deleall(Contact *Con)
{
Contact *cur = Con;
while (cur != NULL)
{
cur = Con->next;
free(Con);
Con = cur;
}
printf("你已经删除所有通讯录\n");
}
void Welcome(void)
{
printf("-----欢迎来到袁强的双链表通信录:------\n");
printf("请执行以下操作:\n\
1:初始化 \n\
2:插入新联系人\n\
3:删除联系人\n\
4:显示联系人\n\
5:删除所有的联系人\n");
}
int main(void)
{
char c = 0;
char str[100];
Welcome();
while (1)
{
scanf_s("%c", &c, 100);
if (c == '#')break;
switch (c)
{
case '1':Initial(); break;
case '2':InsertList(&head); break;
case '3':
printf("输入要删除的名字/电话号码\n");
scanf_s("%s",str,100);
DelList(&head,str);
break;
case '4':PritnList(head); break;
case '5':Deleall(head); break;
}
}
}