您的位置:首页 > 其它

使用指针数组实现bst插入和查找操作

2014-05-21 15:00 253 查看
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct
node* PNode;

#define key int

#define Item int

struct node
{

int index;

Item data;

PNode left;

PNode right;

}__attribute__((aligned(sizeof(int))));
PNode a[100];//暂时定为100,可以先申请内存,然后在申请数组内容的内存,使用指针数组
int inc;//记录插入的个数
int N;//记录数组的大小

#define KEYITEM(A) A

#define Key(A) a[A]->data

#define KLEFT(A) a[A]->left

#define KRIGHT(A) a[A]->right

#define KEYDATA(A) a[A]

#define KNULL -1

#define KSUCCESS -2

#define KLESS -3

#define KMORE -4
static
inline PNode NEW(Item item,PNode l,PNode r,int
aIndex)
{

PNode tp = NULL;

do
{
tp =
malloc(sizeof(struct
node));
}
while (!tp);
tp->index = aIndex;
tp->data = item;
tp->left = l;
tp->right = r;

return tp;
}
void init(int maxN)
{

N = maxN;

for (int i =
0;i < maxN;++i)
{

a[i] = NEW(0,
0, 0,i);
}
}

int STcount()
{

return inc;
}

int searchR(aKey)
{

int count = 0;

for (int i =
0;i < inc;++i)
{

if (Key(i) == aKey)
{

return KSUCCESS;
}
count =
a[i]->index;

PNode temp = NULL;

if (Key(i) < aKey)
{
temp =
a[i]->right;
}

else if (Key(i) > aKey)
{
temp =
a[i]->left;
}

if (!temp)
{

return count;
}

for (;temp;)
{
count = temp->index;

if (temp->data < aKey)
{
temp = temp->left;
}

else if (temp->data > aKey)
{
temp = temp->right;
}

else if (temp->data == aKey)
{

return KSUCCESS;
}
}

if (!temp)
{

return count;
}
}

return count;
}

int STsearch(key aKey)
{

return searchR(aKey);
}

void STinsert(Item aItem)
{

int i = STsearch(KEYITEM(aItem));

if (i >= 0)
{

int j = 0;

while (Key(j)&&(j <
inc))
{
j +=
1;
}

Key(j) = KEYITEM(aItem);

if (Key(i) <
Key(j))
{

KRIGHT(i)= KEYDATA(j);
}

else if (Key(i) >
Key(j))
{

KLEFT(i) = KEYDATA(j);
}
++inc;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐