/*已知长度为n的线性表A采用顺序存储结构,请写一个时间复杂度为O(n)空间复杂度为O(1)
的算法,该算法可删除线性表中所有值为item的数据元素*/
#include<iostream>
using namespace std;
const int MAXSIZE = 100;
struct SqList
{
int *elem;
int length;
};
/*
typedef struct
{
int *elem;
int length;
}SqList;
*/
//初始化
int InitList(SqList &L,int *a,int n)
{
L.elem = new int[n];
if (!L.elem) return 0;
for (int i = 0; i < n; i++)
L.elem[i] = a[i];
L.length = n;
return 1;
}
//输出函数
void PrintList(SqList L)
{
cout << "元素个数为" << L.length << endl;
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << " ";
}
//功能函数
void fun(SqList &L,int e)
{
int k = 0;
for (int i = 0; i < L.length; i++)
{
if (L.elem[i] != e)
{
L.elem[k] = L.elem[i];
k++;
}
}
L.length = k;//一定不能丢
}
int main()
{
int a[6] = { 2,4,2,1,2,3 };
int e;
SqList L;
InitList(L, a, 6);
PrintList(L);
cout << "输入要删除的元素:";
cin >> e;
fun(L, e);
PrintList(L);
system("pause");
return 0;
}