已知长度为n的线性表A采用顺序存储结构,请写一个时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法可删除线性表中所有值为item的数据元素。

语言:C++

#include <iostream>
using namespace std;
typedef int ElemType;

//定义
#define MAXSIZE 100
typedef struct
{ElemType *elem;
int length;}SqList;

//创建
void CreateList(SqList &L)
{
    int i;
    L.elem=new ElemType[MAXSIZE];
    if(!L.elem) cout<<"创建失败!"<<endl;
    cout<<"请输入线性表的长度,不能大于"<<MAXSIZE<<':'<<endl; cin>>L.length;
    cout<<"请依次输入表中元素:"<<endl;
    for(i=0;i<L.length;i++)
        cin>>L.elem[i];
    cout<<"创建完成!"<<endl;
}


//输出表
void display(SqList L)
{
    int i;
    cout<<'[';
    for(i=0;i<L.length;i++)
        {if (i==L.length-1)cout<<L.elem[i];
        else cout<<L.elem[i]<<',';}
    cout<<']'<<endl;
}

void ChooseList_L(SqList &L,int item)
{
    int i=0;int j=0;int k;int count=0;
    for(k=0;k<L.length;k++)
    {
        if(L.elem[k]!=item)
        {
            L.elem[j]=L.elem[i];
            i++;
            j++;

        }
        else
        {
            i++;
            count++;
        }

    }
    L.length-=count;


}
int main()
{
    SqList L;int item;

    CreateList(L);
    cout<<"当前线性表为:"<<endl;
    display(L);

    cout<<"删除表中所有值为item的数据元素,请输入item:"<<endl;
    cin>>item;

    ChooseList_L(L,item);

    cout<<"选择删除后线性表为:"<<endl;
    display(L);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42451835/article/details/83504185