#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct people //创建通讯录结构体
{
char name[20];
char nub[20];
struct people *Next;
}Record,*SRecord;
SRecord stuhead;
SRecord Initlist(SRecord stuhead) //创建链表
{
Record *p,*q;
stuhead=(Record *)malloc(sizeof(Record)); //创建一个头结点
if(stuhead == NULL)
{
printf("创建结点失败\n");
return stuhead;
}
p=stuhead;
printf("你想创建几个结点\n");
int i,n;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q=(Record *)malloc(sizeof(Record));
printf("请输入通讯录的:人名\t号码\t\n");
scanf("%s%s",q->name,q->nub);
p->Next=q;
p=q;
}
p->Next=NULL;
return stuhead;
}
SRecord Insertlist(SRecord stuhead) //从尾部插入
{
Record *p,*q,*t;
p=stuhead;
while(p != NULL)
{
q=p;
p=p->Next;
}
if(p == NULL)
{
t=(Record *)malloc(sizeof(Record));
printf("请输入通讯录的:人名\t号码\t\n");
scanf("%s%s",q->name,q->nub);
q->Next=t;
t->Next=NULL;
}
return stuhead;
}
int Seek(SRecord stuhead) //遍历链表
{
Record *p;
p=stuhead->Next;
printf("通讯录的所有信息如下\n");
while(p != NULL)
{
printf("名字:%s\t号码:%s\n",p->name,p->nub);
p=p->Next;
}
return 0;
}
int Find(SRecord stuhead)
{
Record *p=stuhead->Next;
printf("请输入你想查找的人名\n");
char sname[20];
scanf("%s",sname);
while(p != NULL)
{
if(strcmp(sname,p->name) == 0)
{
printf("%s的电话号码为:%s\n",p->name,p->nub);
return 0;
}
p=p->Next;
}
if(p == NULL)
{
printf("未找到该人\n");
}
return 0;
}
SRecord Delete(SRecord stuhead)
{
Record *p,*q;
p=stuhead->Next;
printf("请输入你想删除的人名\n");
char dname[20];
scanf("%s",&dname);
if(strcmp(dname,p->name) == 0) //在首元结点处
{
printf("已删除\n");
stuhead->Next=p->Next;
return stuhead;
}
while(p != NULL) //在中间位置
{
q=p;
p=p->Next;
if(strcmp(dname,p->name) == 0)
{
printf("已删除\n");
q->Next=p->Next;
return stuhead;
}
}
if(p == NULL)
{
printf("未找到该人名\n");
}
return stuhead;
}
int menu(void)
{
printf("......................\n");
printf("...... 通讯录.........\n");
printf(".....1:创建号码.......\n");
printf(".....2:查找号码.......\n");
printf(".....3:遍历通讯录.....\n");
printf(".....4:删除号码.......\n");
printf(".....5:插入号码.......\n");
printf("..... 0:退出..........\n");
printf("......................\n");
return 0;
}
int main()
{
SRecord head;
int input;
do{
menu();
printf("请输入你的选择\n");
scanf("%d",&input);
switch(input)
{
case 1:
head=Initlist(head);
break;
case 2:
Find(head);
break;
case 3:
Seek(head);
break;
case 4:
head=Delete(head);
break;
case 5:
head=Insertlist(head);
break;
case 0:
printf("退出\n");
break;
default :
printf("请重新输入\n");
break;
}
}while(input);
return 0;
}