已知长度为n (n<20) 的线性表A采用顺序存储结构,请写一时间复杂度为0(n)、空间复杂度为0(1)的算法,该算法删除线性表中所有值为item的数据元素。(O(1)表示算法的辅助空间为常量)。
本人初学者,代码有个人风格,不过还是很好懂的,请见谅。
#include
using namespace std;
typedef int LeleType;
#define MaxSize 100
typedef struct
{
LeleType *Lele;
int length;
}SeqList;
int FirstList(SeqList &L)
{
int i;
int len;
L.Lele = new LeleType[MaxSize];
if(!L.Lele)
{
return 0;
}
cin >> len;
L.length = len;
for(i = 0; i<L.length; i++)
{
cin >> L.Lele[i];
}
}
void ListDelete(SeqList &L,int item)
{
int i;
int j = 0;
for(i=0; i<L.length;i++)
{
if(L.Lele[i] != item)
{
L.Lele[j] = L.Lele[i];
j++;
}
}
L.length = j;
}
int main()
{
SeqList L;
int n;
FirstList(L);
cin >> n;
ListDelete(L,n);
for(int i=0;i<L.length;i++)
cout << L.Lele[i] << endl;
return 0;
}