双链表写通讯录

双链表写通讯录

本人用双链表写的一个通讯录,代码如下:
#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
			{
				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;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值