2021-09-16

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值