按值查找顺序表。请在程序中建立一个含有10个元素,分别是1,2,3,4,5,6,7,8,9,10的顺序表。然后等候用户输入要查找的元素值,如顺序表中有该元素,则输出该元素位序,否则输出查找失败。
【输入】要查找的元素值
【输出】该元素位序 或 查找失败
代码
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int ElemType;
typedef int Status;
#define MAXSIZE 10
typedef struct{
ElemType *elem;
int length;
}SqList;
Status InitList_Sq(SqList &L){ //算法2.1 顺序表的初始化
//构造一个空的顺序表L
L.elem=new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间
if(!L.elem) exit(OVERFLOW); //存储分配失败
L.length=0; //空表长度为0
return OK;
}
Status GetElem(SqList L,int i,ElemType &e) //算法2.2 顺序表的取值
{
if (i<1||i>10) return ERROR;
e=L.elem[i-1];
return OK;
}
void DestroyList(SqList &L)
{
if (L.elem) delete[]L.elem; //释放存储空间
}
void ClearList(SqList &L)
{
L.length=0; //将线性表的长度置为0
}
int LocateElem_Sq(SqList L,ElemType e){ //算法2.3 顺序表的查找
//顺序表的查找
for(int i=0;i<10;i++)
if(L.elem[i]==e) return i+1;
return 0;
}
int main()
{
SqList L;
int i;
int e;
cin>>e;
if(e>1&&e<10)
cout<<e<<"是第"<<e<<"个数\n\n";
else
cout<<" 查找失败\n\n";
DestroyList(L);
return 0;
}