【数据结构】算法9.1 顺序表查找-顺序查找

来源:互联网 发布:美工专用笔记本 编辑:程序博客网 时间:2024/05/18 00:30
#include<stdio.h>#include<string.h>#include<stdlib.h>#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2#define LIST_INIT_SIZE 100 //存储空间的初始分配量#define EQ(a,b) ((a) == (b))#define LT(a,b) ((a) <  (b))#define LQ(a,b) ((a) <= (b))typedef int Status;typedef int KeyType;typedef struct{    KeyType key;    int weight;}ElemType;typedef struct{    ElemType *elem; //unit elem[0] keep NULL    int length;   //length of table}SSTable;/*******************************声明部分****************************************/Status InitTable(SSTable *L);Status CreateTalbe(SSTable *L);int Serch_Seq(SSTable ST,KeyType key);//在顺序表ST中顺序查找其关键字等于key的数据元素/*******************************函数部分****************************************/Status InitTable(SSTable *L){    (*L).elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));    if(!(*L).elem)        exit(OVERFLOW);    (*L).length = 0;    return OK;}Status CreateTalbe(SSTable *L){    int i; /*   printf("请输入顺序表的长度:");    scanf("%d",&L->length);    for(i = 1;i<=L->length;i++){        printf("请输入第 %d 个元素的值:",i);        scanf("%d",&L->elem[i].key);    }*/    for(i = 1;i<=5;i++)        L->elem[i].key = i;    L->length = 5;    return OK;}int Serch_Seq(SSTable ST,KeyType key){    int i;    ST.elem[0].key = 0;  //Set the sentinel //flag    for(i = ST.length; !EQ(ST.elem[i].key,key); --i);  //从后往前找    return i;  //找不到时,i = 0;}/*******************************主函数部分**************************************/int main(){    SSTable L;    InitTable(&L);    CreateTalbe(&L);    printf("\n在顺序表 12345 中寻找 3 的位置\n");    printf("\n3 的位置在:%d\n",Serch_Seq(L,3));    return 0;}

这里写图片描述

0 0
原创粉丝点击