6-1 顺序表的查找操作 (10分)

本题要求实现一个函数,要求从顺序表中查找指定元素,并返回第一个查找成功的元素在表中的位置序号,若查找失败,则返回0;

函数接口定义:

int LocateElem(SqList L,ElemType e);

其中SqList结构定义如下:

typedef struct{
    ElemType *elem;
    int length;
 }SqList;

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
typedef int ElemType;
typedef struct{
    ElemType *elem;
    int length;
 }SqList;
void InitList(SqList &L);/*细节在此不表*/
int LocateElem(SqList L,ElemType e);

int main()
{
    SqList L;
    InitList(L);
    ElemType e;
    int p;
    scanf("%d",&e);
    p=LocateElem(L,e);
    printf("The position of %d in SequenceList L is %d.",e,p);
    return 0;
}

/* 请在这里填写答案 */

###输入格式: 输入数据有1行,首先给出以-1结束的顺序表元素值(不超过100个,-1不属于顺序表元素),然后是待查找的元素值。所有数据之间用空格分隔。

输入样例:

2 6 4 9 13 -1 2

输出样例:

The position of 2 in SequenceList L is 1.

答案样例

int LocateElem(SqList L,ElemType e){//创作不易,点个赞吧,新春快乐~
	for(int i=0; i<L.length; i++)
		if(L.elem[i]==e)
			return i+1;
	return 0;
}

感谢您的阅读,点个赞吧❤⭐

更多推荐