C dictionary implementation

Source: Internet
Author: User

//// // 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

========================================================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.