Skip to content

Instantly share code, notes, and snippets.

@wasade
Created January 28, 2014 22:29
Show Gist options
  • Save wasade/8677925 to your computer and use it in GitHub Desktop.
Save wasade/8677925 to your computer and use it in GitHub Desktop.
Symbol table based off of Sedgewick (http://www.amazon.com/Algorithms-Parts-1-4-Fundamentals-Structures/dp/0201314525). This code can be considered to be BSD.
#include <stdlib.h>
#include "symbol_table.h"
typedef struct STNode* stlink;
struct STNode {
int index, d;
stlink l, m, r; // left, middle, right
};
static stlink head;
static int val, N;
/* STinit
*
* Initialize the symbol table
*/
void STinit() {
head = NULL;
N = 0;
}
/* STnew
*
* create a new member of the symbol table
*/
static stlink STnew(int d) {
stlink x = malloc(sizeof(*x));
x->index = -1;
x->d = d;
x->l = NULL;
x->m = NULL;
x->r = NULL;
return x;
}
/* STindexR
*
* Recursively determine where to place a new member in the table
*/
static stlink STindexR(stlink h, char* v, int w) {
int i = v[w];
if(h == NULL)
h = STnew(i);
if(i == 0) {
if(h->index == -1)
h->index = N++;
val = h->index;
return h;
}
if(i < h->d)
h->l = STindexR(h->l, v, w);
if(i == h->d)
h->m = STindexR(h->m, v, w+1);
if(i > h->d)
h->r = STindexR(h->r, v, w);
return h;
}
/* STindex
*
* Driver method, place into the symbol table
*/
int STindex(char *key) {
head = STindexR(head, key, 0);
return val;
}
#ifndef MCDONALD_SYMBOLTABLE_H
#define MCDONALD_SYMBOLTABLE_H
#endif
int STindex(char *key);
void STinit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment