//在主表中插入新项,将在副表的表头插入,如果在主表中,已经有这个项,就在副表中查找到后,放在副表的表头
//在主表中删除项,将在副表中放在副表的表头,说明这个项刚被访问过
//查找有递归写法和非递归
//查找和删除用一个函数完成,查找和插入也用一个函数完成
//数组下标从1开始
//这里没有考虑到表满的情况,如果表满,就要从新分配空间,然后在插入新项
typedef int Key;
typedef int Item;
#define ITEMNULL 0
static Item* st;
static Item* subSt;
#define key(A) (A)
static int N;//数组个数
void STinit(int maxN)
{
N = 0;
st = malloc(sizeof(Item)*(maxN+1));
if (!st)
{
printf("STinit create failed");
}
memset(st, 0, sizeof(Item)*(maxN+1));
subSt = malloc(sizeof(Item)*(maxN+1));
if (!subSt)
{
printf("subSt create failed");
}
memset(subSt, 0, sizeof(Item)*(maxN+1));
}
int STcount()
{
return N;
}
Item searchR(int l,int r,Key aKey)
{
int m = (l+r)/2;
if (l > r)
{
return ITEMNULL;
}
else if (aKey == key(st[m]))
{
return st[m];
}
else if(aKey < key(st[m]))
{
return searchR(l,m-1, aKey);
}
else
{
return searchR(m+1,r, aKey);
}
}
Item searchNR(int l,int r,Key aKey)
{
Item tmp = ITEMNULL;
if (l > r)
{
return ITEMNULL;
}
int m = 0;
while (l < r)
{
m = (l+r)/2;
if (aKey == key(st[m]))
{
tmp = key(st[m]);
break;
}
else if (aKey < key(st[m]))
{
r = m - 1;
}
else
{
l = m + 1;
}
}
return tmp;
}
void moveST(int aIndex,Key aKey)
{
int n = -1;
if (aIndex < 0)
{
n = N;
}
else if (aIndex > 0)
{
for (int j = 1;j <= N;j +=1)
{
if (subSt[j] == aKey)
{
n = j;
break;
}
}
}
int i = n ;
for (;i > 1;i -=1)
{
subSt[i] = subSt[i-1];
}
if (aIndex)
{
subSt[i] = aKey;
}
}
Item STsearch(Key aKey)
{
int j = 0;
for (j = 1;j <= N;++j)
{
if (aKey == key(st[j]))
{
moveST(1,aKey);
return st[j];//过滤掉相同项
}
if (aKey < key(st[j]))
{
break;
}
}
return ITEMNULL;
}
void STinsert(Item aItem)
{
int j = ++N;
Key v = key(aItem);
while ((j > 1)&&(v < key(st[j-1])))
{
st[j] = st[j-1];
--j;
}
st[j] = aItem;
moveST(-1,key(aItem));
}
void STdelete(Item aItem)
{
int i = 0;
int j = 0;
int finder = -1;
for (i = 1;i <= N;++i)
{
if (st[i] == aItem)
{
moveST(1,key(aItem));
finder = i;
break;
}
}
if (finder == -1)
{
printf("finder failed");
return;
}
for (j = finder;j <= N; ++j)
{
st[j] = st[j+1];
}
//st[N-1] = 0;
--N;
}
void STsearchInsert(Item aItem)
{
int i = 0;
Key v = key(aItem);
for (i = 1;i <= N;++i)
{
if (v == key(st[i]))
{
return;
}
else if(v < key(st[i]))
{
break;
}
}
int j = ++N;
while ((j > i)&&(v < key(st[j-1])))
{
st[j] = st[j-1];
--j;
}
st[j] = aItem;
}
Item STselect(int k)
{
return st[k];
}
void STvist(Item aItem)
{
printf("%d ",aItem);
}
void STsort(void (*visit)(Item))
{
for (int i = 1;i <= N;++i)
{
if (st[i] != ITEMNULL)
{
visit(st[i]);
}
}
}