数据结构 | 考研代码题之顺序表 | 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;
}
相关推荐
Qt学视觉9 分钟前
AI2-Paddle环境搭建
c++·人工智能·python·opencv·paddle
廋到被风吹走31 分钟前
【LangChain4j】特点功能及使用场景
后端·python·flask
Eward-an35 分钟前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4381 小时前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
皙然1 小时前
彻底吃透红黑树
数据结构·算法
t198751281 小时前
TOA定位算法MATLAB实现(二维三维场景)
开发语言·算法·matlab
喵手1 小时前
Python爬虫实战:用代码守护地球,追踪WWF濒危物种保护动态!
爬虫·python·爬虫实战·濒危物种·零基础python爬虫教学·wwf·濒危物种保护动态追踪
梦想的旅途21 小时前
如何通过 QiWe API 实现企业微信主动发消息
开发语言·python
jllllyuz1 小时前
粒子群算法解决资源分配问题的MATLAB实现
开发语言·算法·matlab
喵手1 小时前
Python爬虫实战:自动化抓取 Pinterest 热门趋势与创意!
爬虫·python·爬虫实战·pinterest·零基础python爬虫教学·采集pinterest热门趋势·热门趋势预测