建立一个顺序表,用顺序查找的方法对其实施查找。
顺序表的类型描述:
#define MAXSIZE 50
typedef int ElemType;
typedef struct
{
ElemType *R;
int length;
} SSTable;
输入格式:
第一行输入一个整数n,表示顺序表的元素个数。
第二行行输入n个数字,依次为表内元素值。
第三行输入一个要查找的值。
输出格式:
输出这个值在表中的位置。如果没有找到,输出NOT FOUND
。
输入样例:
5
9 5 3 7 6
7
输出样例:
4
输入样例:
5
9 5 3 7 6
8
输出样例:
NOT FOUND
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
typedef int ElemType;
typedef struct
{
ElemType *R;
int length;
} SSTable;
// 初始化顺序表
void InitList(SSTable *L, int n)
{
L->R = (ElemType *)malloc((n + 1) * sizeof(ElemType));
if (!L->R)
{
exit(EXIT_FAILURE);
}
for (int i = 1; i <= n; ++i)
{
scanf("%d", &L->R[i]);
}
L->length = n;
}
// 顺序查找
int SequentialSearch(SSTable *L, ElemType key)
{
L->R[0] = key; // 设置哨兵
int i = L->length;
while (L->R[i] != key)
{
--i;
}
return i; // 如果i为0,表示查找失败
}
int main()
{
SSTable L;
int n, key, result;
// 输入元素个数
scanf("%d", &n);
// 初始化顺序表
InitList(&L, n);
// 输入要查找的值
scanf("%d", &key);
// 进行顺序查找
result = SequentialSearch(&L, key);
// 输出结果
if (result != 0)
{
printf("%d\n", result);
}
else
{
printf("NOT FOUND\n");
}
// 释放内存
free(L.R);
return 0;
}