#include <stdio.h>
#define MaxSize 10 //array size
/*create struct for data*/
typedef struct{
int data[MaxSize];
int length; //current table's length
}SqList;
/*insert data to array*/
int ListInsert(SqList &L, int i, int e){
if(i<1 || i>L.length+1)
return -1;
if(L.length>=MaxSize)
return -2;
for(int j=L.length; j>=i; j--)
L.data[j] = L.data[j-1];
L.data[i-1] = e;
L.length++;
return 1;
}
/*delete data from table*/
int ListDelete(SqList &L, int i, int &e){
if(i<1 || i>L.length)
return -1;
e = L.data[i-1];//give the deleted data to e
for(int j=i; j<L.length; j++){
L.data[j-1] = L.data[j];
}
L.length--;
return 1;
}
/* find data by location*/
int GetElem(SqList &L, int i){
if(i<1 || i>L.length)
return 0;
return L.data[i-1];
}
/*find by value*/
int GetElem1(SqList &L, int e){
for(int j=0; j<L.length; j++)
if(L.data[j] == e)
return j+1;
return 0;
}
/*Initialize data*/
void InitList(SqList &L){
L.length = 0;
}
int main(void) {
SqList L;
InitList(L);
/*insert*/
ListInsert(L,1,2);
ListInsert(L,2,8);
ListInsert(L,3,4);
ListInsert(L,4,5);
ListInsert(L,5,6);
for(int i=0; i<L.length; i++)
printf("data[%d]=%d\n",i,L.data[i]);
/*delete*/
int e = -1;//bring the deleted data
if(ListDelete(L, 2, e))
printf("The second element(%d) was deleted\n",e);
else
printf("fail to delete!");
for(int i=0; i<L.length; i++)
printf("data[%d]=%d\n",i,L.data[i]);
/*find data by location*/
int value = GetElem(L,2);
printf("The second element is %d\n",value);
/*find data by value*/
int value1 = GetElem1(L,5);
printf("The %dth element is 5\n",value1);
return 0;
}
1、插入操作的时间复杂度计算:
2、删除操作的时间复杂度:
3、查找操作的时间复杂度计算:
按位:
按值: