数据结构 | 考研代码题之顺序表 | 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;
}
相关推荐
Yzzz-F3 分钟前
Problem - D2 - Codeforces [插入计数]
算法
图图的点云库3 分钟前
点云深度学习算法概述
人工智能·深度学习·算法
旗讯数字3 分钟前
智破纸质壁垒 赋能医药合规——旗讯数字医药注册批件纸质文档智能识别与结构化提取对接解决方案
数据结构·ocr·合规审查
2501_9249526910 分钟前
设计模式在C++中的实现
开发语言·c++·算法
菜鸟小九12 分钟前
hot100(71-80)
java·数据结构·算法
代码探秘者13 分钟前
【大模型应用】4.分块之六大策略
java·数据结构·后端·python·spring
不想看见40414 分钟前
Implement Queue using Stacks栈和队列--力扣101算法题解笔记
笔记·算法·leetcode
DeepModel16 分钟前
【统计检验】T检验
算法
齐齐大魔王21 分钟前
虚拟机网络无法连接
linux·网络·c++·python·ubuntu
ycjunhua25 分钟前
Notebooklm for windows本地安装使用
python·webstorm