//// // C Dictionary data structure ////////////
Struct NLIST {/* Table entry :*/
Struct NLIST * Next;/* next entry in chain */
Char * Name;/* defined name */
Char * defn;/* Replacement text */
};
# Define hashsize 101
Static struct NLIST * hashtab [hashsize];/* pointer table */
/* Hash: Form hash value for string S */
Unsigned Hash (char * s)
{
Unsigned hashval;
For (hashval = 0; * s! = '\ 0'; s ++)
Hashval = * s + 31 * hashval;
Return hashval % hashsize;
}
/* Lookup: Look for S in hashtab */
Struct NLIST * Lookup (char * s)
{
Struct NLIST * NP;
For (Np = hashtab [Hash (s)]; NP! = NULL; Np = NP-> next)
If (strcmp (S, NP-> name) = 0)
Return NP;/* found */
Return NULL;/* not found */
}
Char * strdup (char *);
/* Install: Put (name, defn) in hashtab */
Struct NLIST * install (char * Name, char * defn)
{
Struct NLIST * NP;
Unsigned hashval;
If (Np = Lookup (name) = NULL) {/* not found */
NP = (struct NLIST *) malloc (sizeof (* NP ));
If (Np = NULL | (NP-> name = strdup (name) = NULL)
Return NULL;
Hashval = hash (name );
NP-> next = hashtab [hashval];
Hashtab [hashval] = NP;
} Else/* already there */
Free (void *) NP-> defn);/* free previous defn */
If (NP-> defn = strdup (defn) = NULL)
Return NULL;
Return NP;
}
Char * strdup (char * s)/* make a duplicate of S */
{
Char * P;
P = (char *) malloc (strlen (s) + 1);/* + 1 for '\ 0 '*/
If (P! = NULL)
Strcpy (P, S );
Return P;
}
/* DIC opreation interface */
Void dic_put (char * Key, char * value)
{
Install (Key, value );
}
Char * dic_value_for_key (char * key)
{
Char * ret = "";
Struct NLIST * NP = Lookup (key );
If (NP! = NULL ){
Ret = NP-> defn;
}
Return ret;
}
//// // C Dictionary data structure end ////////////
=============== Call example ==============================
Dic_put ("1", "hello ");
Printf ("value ==>>% s \ n", dic_value_for_key ("1 "));
Output:
Value ==>> hello
========================================================