C语言通讯录之链表

来源:互联网 发布:网络说风油精什么意思 编辑:程序博客网 时间:2024/05/08 05:07
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <malloc.h>#include <conio.h>#define N 3typedef struct node{   char name[20];   struct node *next;}stud;stud* Creat(int n){   stud *h,*s,*p;   int i;   if((h=(stud *)malloc(sizeof(stud)))==NULL)   {    printf("内存不够!");       exit(0);   }   h->name[0]='\0';   h->next=NULL;   p=h;   for(i=0;i<n;i++)   {      if((s=(stud *)malloc(sizeof(stud)))==NULL)      {   printf("内存不够!");   exit(0);  }  p->next=s;      printf("请输入第%d个人的姓名",i+1);      scanf("%s",s->name);      s->next=NULL;      p=s;    }    return (h);}stud* Search(stud *h,char *y){   stud *p;   p=h->next;   while(p!=NULL)   {      if(strcmp(p->name,y)==0)       return (p);        else       p=p->next;          }   if(p==NULL)   printf("未查找到该同学数据!");   return 0;}stud* SearchFore(stud *h,char *y){   stud *s,*p;   p=h->next;   s=p->next;   while(s!=NULL)   {            if(strcmp(s->name,y)==0)       return (p);        else  {       p=p->next;           s=s->next;         }   }   if(s==NULL)   printf("未查找到该同学数据!");   return 0;}void Insert(stud *p){   stud *s;   if((s=(stud *)malloc(sizeof(stud)))==NULL)   {     printf("内存不够!");     exit(0);   }   printf("\n请输入你要插入的人的姓名:");   scanf("%s",s->name);    s->next=p->next;   p->next=s;}void Skim(stud *h){   stud *p;   p=h->next;   while(p)    {       printf("%s",p->name);       p=p->next;     }}void Del(stud *x,stud *y){    stud *s;   s=y;   x->next=y->next;   free(s);}void Quit(){      exit(0);}void menu(void){   system("cls");printf("\t\t\t单链表C语言实现实例\n");printf("\t\t————————————————\n");printf("\t\t \n");printf("\t\t [1] 建 立 新 表 \n");printf("\t\t [2] 查 找 数 据 \n");printf("\t\t [3] 插 入 数 据 \n");printf("\t\t [4] 删 除 数 据 \n");printf("\t\t [5] 打 印 数 据 \n");printf("\t\t [6] 退 出 \n");printf("\t\t \n");printf("\t\t 如未建立新表,请先建立! \n");printf("\t\t \n");printf("\t\t————————————————\n");printf("\t\t 请输入你的选项(1-6):");}void main(){   int choose;   stud *head,*searchpoint,*forepoint;   char fullname[20];    while(1)   {      menu();      scanf("%d",&choose);      switch(choose)       { case 1:head=Creat(N);        break; case 2:printf("输入你所要查找的人的姓名:");scanf("%s",fullname);    searchpoint=Search(head,fullname);    printf("你所查找的人的姓名为:%s",*&searchpoint->name);    printf("\n按回车键回到主菜单。");    getchar();getchar();    break;case 3: printf("输入你要在哪个人后面插入:");scanf("%s",fullname);searchpoint=Search(head,fullname);printf("你所查找的人的姓名为:%s",*&searchpoint->name);Insert(searchpoint);Skim(head);printf("\n按回车键回到主菜单。");getchar();getchar();break;case 4: Skim(head);    printf("\n输入你所要删除的人的姓名:");    scanf("%s",fullname);    searchpoint=Search(head,fullname);    forepoint=SearchFore(head,fullname);    Del(forepoint,searchpoint);    break;case 5: Skim(head);    printf("\n按回车键回到主菜单。");    getchar();getchar();   break;case 6: Quit();    break;default:printf("你输入了非法字符!按回车键回到主菜单。"); system("cls");menu();getchar();        }    }}

     学习笔记:当初学习链表时,对部分代码进行了借鉴.实战经验很重要.需要多多动手.