数据结构 | 考研代码题之顺序表 | 1 查找L中值为e的数据元素若找到则返回其下标,若找不到则返回-1

文章目录

  • [1 题目](#1 题目)
  • [2 题解](#2 题解)

1 题目

假设有一个顺序表 L,其存储的所有数据元素均为不重复的正数,查找L中值为e的数据元素,若找到则返回其下标,若找不到则返回-1。

2 题解

C语言代码:

c 复制代码
/*
    假设有一个顺序表 L,其存储的所有数据元素均为不重复的正数,查找L中值为e的数据元素,若找到则返回其下标,若找不到则返回-1。
*/
#include <stdio.h>
#include <stdlib.h> //包含了随机数生成函数 rand() 和种子设置函数 srand()。
#include <time.h>   // 包含了时间处理函数,用于获取当前时间作为种子。
#define MaxSize 50

typedef struct L {
    int data[MaxSize];
    int length;
}SqList;

int Search_e(SqList L, int e) {
    printf("%d", L.length);
    for (int i = 0; i < L.length; i++) { // 遍历顺序表 L
        if (L.data[i] == e) // 若找到值为 e 的元素,则返回其下标
            return i;
    }
    return -1; // 若跳出 for 循环则代表未找到值为 e 的元素,则返回-1
}

int main() {
    SqList L;
    L.length = 10;
    srand(time(NULL)); // 设置种子,使用当前时间作为种子,确保每次运行生成的随机数不同

    for (int i = 0; i < 10; i++) {
        int random_number = rand() % 100 + 1; // 生成1到100之间的随机数。
        L.data[i] = random_number;

    }
    for (int i = 0; i < 10; i++) {
        printf("%d ", L.data[i]);
    }
    
    int e;
    scanf("%d", & e);
    int res = Search_e(L, e);
    printf("\n%s%d", (res == -1) ? "未找到该元素" : "找到的元素下标为", res);
    return 0;
}
相关推荐
Closet1231 分钟前
Codeforces 2025/6/11 日志
c++·算法·codeforces
Tom Boom11 分钟前
Pytest断言全解析:掌握测试验证的核心艺术
自动化测试·python·测试开发·pytest
Cyrus_柯14 分钟前
网络编程(数据库:SQLite)
linux·c语言·数据库·sqlite
Jamesvalley25 分钟前
【Django】性能优化-普通版
python·性能优化·django
StackOverthink30 分钟前
[特殊字符] Altair:用Python说话,让数据自己讲故事!!!
开发语言·python·其他·信息可视化
水饺编程1 小时前
MFC 第一章概述
c语言·c++·windows·mfc
緈福的街口1 小时前
【leetcode】36. 有效的数独
linux·算法·leetcode
新中地GIS开发老师1 小时前
2025武汉考研形势分析,趋势、挑战与应对策略
学习·考研·arcgis·大学生·gis开发·webgis·地理信息科学
qq_527887871 小时前
ImportError: cannot import name ‘PfeifferConfig‘ from ‘transformers‘【已解决】
linux·开发语言·python
知舟不叙1 小时前
使用OpenCV和Python进行图像掩膜与直方图分析
人工智能·python·opencv·图像掩膜