数据结构 | 考研代码题之顺序表 | 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;
}
相关推荐
会员源码网7 小时前
使用`mysql_*`废弃函数(PHP7+完全移除,导致代码无法运行)
后端·算法
木心月转码ing8 小时前
Hot100-Day10-T438T438找到字符串中所有字母异位词
算法
HelloReader8 小时前
Wi-Fi CSI 感知技术用无线信号“看见“室内的人
算法
颜酱11 小时前
二叉树分解问题思路解题模式
javascript·后端·算法
zone773911 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant11 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来12 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_12 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
qianpeng89712 小时前
水声匹配场定位原理及实验
算法
haosend13 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化