1. 程式人生 > >使用陣列模擬符號表的程式

使用陣列模擬符號表的程式

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

//插入,查詢,刪除等操作

typedefint Item;

typedefint Key;

staticItem *g_cache;

staticItem *g_Item;

staticint M;

staticint indexX;

void key(Item aItem,Key aKey)

{

   g_Item[aItem] = aKey;

}

Key getKey(Item aItem)

{

   return g_cache

[aItem];

}

void STinit(int n)

{

   g_cache = malloc(sizeof(&g_cache)*n);

   if (!g_cache)

    {

printf("create failed!!!!!");

       return;

    }

   g_Item = malloc(sizeof(&g_Item)*n);

   if (!g_Item)

    {

printf("create failed!!!!!");

       return;

    }

   M = n;

   memset(g_Item,0,sizeof

(&g_Item)*n);

   memset(g_cache,0,sizeof(&g_cache)*n);

}

int STcount()

{

   int count = 0;

   for (int i =0;i < M;++i)

    {

       Item item = g_Item[i];

       if (getKey(item))

        {

            count +=1;

        }

    }

   return count;

}

void STinsert(Item aItem)

{

   g_Item[indexX

++] = aItem;

}

Item STsearch(Key aKey)

{

   Item tempItem = 0;

   for (int i =0;i < M;++i)

    {

       Item item = g_Item[i];

       if (getKey(item))

        {

            tempItem = item;

           break;

        }

    }

   return tempItem;

}

void STdelete(Item aItem)

{

   g_cache[aItem] = 0;

   g_Item[g_cache[aItem]] =0;

}

Item STselect(int aSelect)

{

   return g_cache[g_Item[aSelect]];

}