// idsymtab.cpp // implement idSymbolTable class. #include "idsymtab.h" #include #include idSymbolTable::idSymbolTable() { // constructor. for (int i = 0; i < NUMOFKEYS; i++) idSymTab[i] = NULL; // initialize. for (i = 0; i < MAXCHARS; i++) strTab.str[i] = '@'; // initialize. strTab.freeIndex = 0; idIndex = 0; } idSymbolTable::~idSymbolTable() { // destructor. idSymbolNode* p; idSymbolNode* q; for (int i = 0; i < NUMOFKEYS; i++) { p = idSymTab[i]; while (p != NULL) { q = p->link; delete p; // delete all idSymbolNode which are not NULL. p = q; } // end of while loop. } // end of for loop. } // end of destructor. int idSymbolTable::idHash(char* w) { // define hash function. const unsigned int MAX=65535 - 127; unsigned int sum = 0; for (int i = 0; i < strlen(w); i++) sum = (sum + w[i]) % MAX; return sum % NUMOFKEYS; } void idSymbolTable::printStrTab() { for (int i = 0; i < strTab.freeIndex; i++) { if (strTab.str[i] != '@') cout << strTab.str[i] << " "; } cout << "\nThe freeIndex of strTab is: " << strTab.freeIndex << endl; } void idSymbolTable::printIdSymTab() { for (int i = 0; i < NUMOFKEYS; i++) { if (idSymTab[i] != NULL) { cout << "At index: (" << i << "), there are following idSymbolNode(s):" << endl; // process linked list using while loop. Will do later. } } } void idSymbolTable::searchAndMaybeInsert(char* s, int& idIdx, bool& insertOk) { bool done = false; insertOk = true; int k = 0; char w[STRSIZE], t[2]; t[1] = '\0'; int idHashValue = idHash(s); idSymbolNode* p = idSymTab[idHashValue]; // Process: while ( (p != NULL) && (!done) ) { w[0] = '\0'; k = p->firstChar; while (k < (p->firstChar + p->length) ) { t[0] = strTab.str[k]; strcat(w, t); k++; } // end of inner while loop. if (strcmp(w, s) == 0) { // case w == s idIdx = p->index; done = true; } else { p = p->link; // advance the pointer. } // end of if-else. } // end of outer while loop. if (p == NULL) { int len = strlen(s); if ( (strTab.freeIndex + len) > (MAXCHARS - 1) ) { insertOk = false; idIdx = 0; } else { k = 0; while (k < len) { strTab.str[strTab.freeIndex + k] = s[k]; k++; } // end of while loop. idSymbolNode* q = idSymTab[idHashValue]; p = new idSymbolNode; p->firstChar = strTab.freeIndex; p->length = k; p->index = idIndex; p->link = q; // advance pointer. idSymTab[idHashValue] = p; strTab.freeIndex += k; idIdx = idIndex; idIndex++; } // end if if-else. } // end of outer if. } // end of the method searchAndMaybeInsert().