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

#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;

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值