/*(6)已知长度为n的顺序存储结构表A,写一个时间复杂度为o(n)
空间复杂度为o(1)的算法,删除线性表中所有值为item的数据元素*/
//after all, what's the border of difficulty
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>
#include<cstdlib>//包含exit头文件
#include<math.h>
#include<string>
#define MAXSIZE 100
#define OK 1
#define ERROR 0//宏
typedef int Status;
using namespace std;
typedef struct
{
char name[20];
}
Elemtype;//其实我真的搞不懂了string真的好麻烦
typedef struct
{
Elemtype *data;//基地址
int length;//表长n
}SqList;
Status InitList(SqList &L)
{
L.data=(Elemtype *)malloc(MAXSIZE*sizeof(Elemtype));
//返回给data一个基地址
if(!L.data) exit(OVERFLOW);
L.length=0;
return OK;
}
Status EnterData_Sq(SqList &L)
{//data enter for test
int length; Elemtype e;
cout<<"もう言いたくない、もう…"<<endl;
cin>>length;
cout<<"データ、くれないかなあ?"<<endl;
for(int i=0;i<length;i++)
{
cin>>e.name;
L.data[i]=e;
L.length++;
}
return OK;
}
Status LocateElem(SqList L,Elemtype e)
{//找到第一个item
for(int i=0;i<L.length;i++)//时间复杂度o(n)
{
if(!strcmp(L.data[i].name,e.name)) return i+1;//返回位置序号
}
return ERROR;
}
Status DeleteElem(SqList &L,Elemtype e)
{
int i=LocateElem(L,e);
int step=1;//移动步数
if((i<1)||(i>L.length)) return ERROR;//illegal i
for(int j=i;j<L.length;j++)//时间复杂度为o(n),时间耗费在元素移动上最多移动n-1个
{
if(!strcmp(L.data[j].name,e.name))
{
step++;
}else
{//其余保留
L.data[j-step]=L.data[j];
}
}
L.length=L.length-step;
return OK;
}
void ShowList(SqList L)
{
for(int i=0;i<L.length;i++)
{
cout<<L.data[i].name<<endl;
}
}
void main()
{
SqList L;
Elemtype e;
strcpy(e.name,"1");//简单起见,data为char "1"
InitList(L);
EnterData_Sq(L);
cout<<"all ends all starts:"<<endl;
ShowList(L);
DeleteElem(L,e);
cout<<"what's going on?"<<endl;
ShowList(L);
system("pause");
}
删除线性表中所有值为item的数据元素
最新推荐文章于 2023-03-09 15:31:43 发布