已知长度为n的线性表A,请写一时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性表中所有值为item的数据元素。
item = 3
数组下标 i 0 1 2 3 4 5 6 7 8
顺序表: 1 2 3 4 3 3 5 3 7
#include <iostream>
using namespace std;
typedef int ElemType;
#define Maxsize 100
#define OK 1
#define ERROR 0
typedef struct SqList
{
ElemType data[Maxsize];
int length;
}SqList;
void Init_SqList(SqList& L)
{
L.length = 0;
}
//----------------------------------------核心代码----------------------------------------//
bool delete_x(SqList& L, int x)
{
int k = 0;
if (L.length == 0)
{
cout << "线性表数据为空!!!" << endl;
return ERROR;
}
for (int i = 0; i < L.length; i++)
{
if (L.data[i] != x)
{
L.data[k++] = L.data[i];
}
}
L.length = k;
return OK;
}
//----------------------------------------核心代码----------------------------------------//
/*已知长度为n的线性表A,请写一时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性
表中所有值为item的数据元素。*/
//item = 3
//数组下标 i 0 1 2 3 4 5 6 7 8
//顺序表: 1 2 3 4 3 3 5 3 7
int main(void)
{
SqList L;
Init_SqList(L);
L.data[0] = 1;
L.data[1] = 2;
L.data[2] = 3;
L.data[3] = 4;
L.data[4] = 3;
L.data[5] = 3;
L.data[6] = 5;
L.data[7] = 3;
L.data[8] = 7;
L.length = 9;
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
delete_x(L, 3);
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
return 0;
}