#include<iostream>
typedef int ElementType;
using namespace std;
struct linearList
{
ElementType * data;
int MaxSize;
int Last;
};
typedef struct linearList LinearList;
void InitLinearList(LinearList * L,int sz)
{
if(sz>0)
{
L->MaxSize=sz;
L->Last=0;
L->data=(ElementType *)malloc(sizeof(ElementType)*L->MaxSize);
}
};
bool insertElem(LinearList * L,ElementType x,int i) //i是索引
{
if(i<0||L->Last==L->MaxSize)
return false;
for(int j=L->Last-1;j>=i;j--)
{
L->data[j+1]=L->data[j];
}
L->data[i]=x;
L->Last++;
return true;
}
int LocateElem(LinearList *L,int x)
{
for(int j=0;j<L->Last;j++)
{
if(L->data[j]==x)return j;
}
return -1;
}
int inLocateElem(LinearList * L,int x)
{
for(int j=L->Last-1;j>=0;j--)
{
if(L->data[j]==x)return j;
}
return -1;
}
int numLocateElem(LinearList * L,int x)
{
int XSize=0,j,i=0;
for(j=0;j<L->Last;j++)
{
if(L->data[j]==x)
XSize++;
}
return XSize;
}
void allLocateElem(LinearList * L,int x,int *LocateX)
{
int j,i=0;
for(j=0;j<L->Last;j++)
{
if(L->data[j]==x)
{
LocateX[i]=j;
i++;
}
}
}
int main()
{
int sz,j,Elem,x,*X,XSize;
LinearList * L;
cout<<"请输入线性表的容量";//建立线性表
cin>>sz;
InitLinearList(L,sz);
cout<<"请输入每个数据";
for(j=0;j<sz;j++)
{
cin>>Elem;
insertElem(L,Elem,j);
}
cout<<"请输入查找数据";//查找
cin>>x;
cout<<"正序索引为"<<LocateElem(L,x)<<endl;//正序
cout<<"逆序索引为"<<inLocateElem(L,x)<<endl;//逆序
XSize=numLocateElem(L,x);//查找所有
if(XSize>0)
{
X=(int*)malloc(sizeof(int)*XSize);
allLocateElem(L,x,X);
cout<<"其中所有的索引为";
for(j=0;j<XSize;j++)
cout<<X[j]<<" ";
cout<<endl;
}
return 0;
}
2021-09-16
最新推荐文章于 2021-10-09 18:35:31 发布