查找(基础)

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #define OK 1
  4 #define NO 0
  5 #define TRUE 1
  6 #define FALSE 0
  7 #define ERROR -1
  8 
  9 
 10 typedef int Status;
 11 
 12 typedef int KeyType;//关键字类型
 13 typedef struct
 14 {
 15     int key; //关键字域
 16     float weight;//其他域
 17 }ElemType_Search;//有序表元素类型
 18 
 19 /*0号单元弃用*/
 20 
 21 typedef struct
 22 {
 23     ElemType_Search *elem;  //数据元素存储空间基址,0号元素为空
 24     int length;//表长度
 25 }Table;//查找表
 26 
 27 
 28 Status Create(Table *T,int n);
 29 
 30 void Destroy(Table *T);
 31 
 32 void Traverse(Table T);
 33 
 34 int main(int argc,char**argv){
 35 
 36     Table T;
 37     int num;
 38     printf("1\n函数Create测试..\n");
 39     {
 40         printf("创建一个查找表..\n");
 41         printf("输入查找表中的元素个数\n");
 42         scanf("%d",&num);
 43         Create(&T,num);
 44         printf("\n");
 45     }
 46     printf("3\n函数 Traverse 测试..\n");
 47     {
 48         printf("输出查找表的信息..\n");
 49         Traverse(T);
 50         printf("\n");
 51 
 52     }
 53     printf("2\n函数Destroy 测试..\n");
 54     {
 55         Destroy(&T);
 56         
 57         Traverse(T);
 58     
 59     }
 60 
 61 
 62 
 63 return 0;
 64 
 65 }
 66 
 67 Status Create(Table *T,int n){
 68     int i;
 69     int a;
 70     float b;
 71     T->elem=(ElemType_Search*)malloc((n+1)*sizeof(ElemType_Search));
 72     if(!(T->elem))
 73         exit(ERROR);
 74     for(T->length=0,i=1;i<=n;i++)
 75     {
 76         printf("输入查找表内元素格式为key weight\n");
 77         scanf("%d %f",&a,&b);
 78         //printf("%f",b);
 79         T->elem[i].key=a;
 80         T->elem[i].weight=b;
 81         T->length++;    
 82     }
 83 
 84     return OK;
 85 }
 86 
 87 void Traverse(Table T){
 88     int i;
 89     if(T.length==0||T.elem)
 90         printf("表为空\n");
 91     for(i=0;i<T.length;i++)
 92     {
 93         printf("T.elem[%d].key=%d,T.elem[%d].weight=%f\n",i+1,T.elem[i+1].key,i+1,T.elem[i+1].weight);
 94 
 95     }
 96 
 97 }
 98 
 99 void Destroy(Table *T){
100     if(T->elem)
101         free(T->elem);
102     T->elem=NULL;
103     T->length=0;
104 
105 }

 

posted @ 2017-11-07 19:27  accomplishment  阅读(126)  评论(0编辑  收藏  举报