利用顺序表进行的查找,从头到尾与从尾到头

利用顺序表进行的查找,从头到尾与从尾到头,第1张

利用顺序表进行的查找,从头到尾与从尾到头

注:这是两种不同的方法写的,不可一起保存在一个程序中同时运行

//顺序查找C语言实现
//基本思路:用顺序结构存储数据(数组、链表),从前到后依次查询目标值,
//            如果发现则返回查找到的值,否则返回0.
#include

int FindBySeq(int *ListSeq, int ListLength, int KeyData);

int main()
{
    int TestData[5] = { 34, 35, 26, 89, 56 };
    int retData = FindBySeq(TestData, 5, 89);
    printf("retdata: %dn", retData);
    return 0;
}

int FindBySeq(int *ListSeq, int ListLength, int KeyData)
{
    int length = ListLength;
    for (int i = 0; i < ListLength; i++)
    {
        if (ListSeq[i] == KeyData)
            return i;
    }
    return 0;
}

//按照顺序表从后到尾查找 
#include
#include
#define keyType int
typedef struct {
    keyType key;//查找表中每个数据元素的值
    //如果需要,还可以添加其他属性
}ElemType;

typedef struct{
    ElemType *elem;//存放查找表中数据元素的数组
    int length;//记录查找表中数据的总数量
}SSTable;
//创建查找表
void Create(SSTable **st,int length){
    (*st)=(SSTable*)malloc(sizeof(SSTable));
    (*st)->length=length;
    (*st)->elem =(ElemType*)malloc((length+1)*sizeof(ElemType));
    printf("输入表中的数据元素:n");
    //根据查找表中数据元素的总长度,在存储时,从数组下标为 1 的空间开始存储数据
    for (int i=1; i<=length; i++) {
        scanf("%d",&((*st)->elem[i].key));
    }
}
//查找表查找的功能函数,其中key为关键字
int Search_seq(SSTable *st,keyType key){
    st->elem[0].key=key;//将关键字作为一个数据元素存放到查找表的第一个位置,起监视哨的作用
    int i=st->length;
    //从查找表的最后一个数据元素依次遍历,一直遍历到数组下标为0
    while (st->elem[i].key!=key) {
        i--;
    }
    //如果 i=0,说明查找失败;反之,返回的是含有关键字key的数据元素在查找表中的位置
    return i;
}
int main(int argc, const char * argv[]) {
    SSTable *st;
    Create(&st, 6);
    getchar();
    printf("请输入查找数据的关键字:n");
    int key;
    scanf("%d",&key);
    int location=Search_seq(st, key);
    if (location==0) {
        printf("查找失败");
    }else{
        printf("数据在查找表中的位置为:%d",location);
    }
    return 0;
}

//输入表中的数据元素:
//1 2 3 4 5 6
//请输入查找数据的关键字:
//2
//数据在查找表中的位置为:2


 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5595007.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存