哈哈,又更新啦,2020王道课后习题P18,综合应用题3:将长度为n的顺序表L删除所有值为X的元素,时间复杂度:O(n),空间复杂度:O(1)。这个问题是有陷阱的,一开始要是采用正面的思路去想问题,会出现错误,所以要采用反向思维,选出与X不同的元素存入线性表,采用这种方法才能实现,那还是上代码吧:
# include <stdio.h>
#include <stdlib.h>
# define InitSize 100
#include <time.h>
typedef int ElemType;
typedef struct{
ElemType *data;
int Maxsize,length;
}SqList;
//插入操作
bool ListInsert(SqList &L,int i,ElemType e){
if(i<1||i>L.length+1)
return false;
if(L.length>L.Maxsize)
return false;
for(int j=L.length;j>=i;j++)
L.data[j]=L.data[j-1];
L.data[i-1]=e;
L.length++;
return true;
}
//删除顺序表中所有的X
bool Delete(SqList &L,ElemType x){
int k=0;
for(int i=0;i<L.length;i++)
{
if(L.data[i]!=x){
L.data[k]=L.data[i];
k++;
}
}
L.length=k;
}
int main(){
SqList L;
ElemType e;
L.data=new ElemType[InitSize];
L.length=0;
L.Maxsize=100;
for(int t=1;t<=5;++t)
{
ListInsert(L,t,t);
}
for(i