数据结构 | 考研代码题之顺序表 | 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;
}
相关推荐
前端小L17 小时前
回溯算法专题(八):精细化切割——还原合法的「IP 地址」
数据结构·算法
Tandy12356_17 小时前
手写TCP/IP协议——IP层输出处理
c语言·网络·c++·tcp/ip·计算机网络
吴佳浩1 天前
大模型量化部署终极指南:让700亿参数的AI跑进你的显卡
人工智能·python·gpu
Hcoco_me1 天前
大模型面试题17:PCA算法详解及入门实操
算法
跨境卫士苏苏1 天前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代
大数据·人工智能·算法·亚马逊·防关联
diegoXie1 天前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条1 天前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
七牛云行业应用1 天前
解决OSError: No space left... 给DeepSeek Agent装上无限云硬盘
python·架构设计·七牛云·deepseek·agent开发
云雾J视界1 天前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
Xの哲學1 天前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算