C中的Trie Node实现

时间:2014-10-19 05:49:54

标签: c trie

我在使用Trie数据结构的LZW算法中工作。我遇到的问题是我的函数InsertTrie应该添加一个新节点并链接到前一个

enter code here
typedef struct TrieNode {
    short codes[256];
    struct *TrieNode links[258];
} TrieNode;
typedef struct LZWCmp {
    TrieNode *head;   * Head pointer to first TrieNode 
    CodeSink sink;    * Code sink to send bits to 
    void *sinkState;  * Unknown object to send to sink for state 
    int nextCode;     * Next code to be assigned 
    int numBits;      * Number of bits per code currently 
    int maxCode;      * Max code that fits in numBits bits 
    UInt nextInt;     * Partially-assembled next int of output 
    int bitsUsed;     * Number of valid bits in top portion of nextInt 
    TrieNode *curLoc; * Current position in trie 
    short lastSym;    * Most recent symbol encoded 
} LZWCmp

void InsertTrie(LZWCmp *cmp, UChar sym) {
    int init = 0;

    if (cmp->curLoc == NULL) {
    printf("Current Code %u\n", CurCode);
    cmp->curLoc = malloc(sizeof(TrieNode));
    do {
        cmp->curLoc->codes[init] = -1;
        cmp->curLoc->links[init] = NULL;
    } while(++init < NUM_SYMS);

    cmp->curLoc->codes[sym] = CurCode;
 }


int TrieTraverse(LZWCmp *cmp, char *sym) {
    UChar init = 0, result; 
    int size = 1;

    if (cmp->curLoc == NULL) 
        return FALSE;

    do {
        if (init == *sym) {
            cmp->lastSym = cmp->curLoc->codes[init]; // Pack Code
            cmp->curLoc = cmp->curLoc->links[init];
            return TRUE;
        }
    } while(++init < NUM_SYMS && cmp->curLoc != NULL);


}

CurCode是一个静态变量,它跟踪最后一个代码并插入到trie Tree中我首先遍历Trie Node然后我将curLoc设置为特定链接,这个链接多次将为NULL并且我malloc创建一个新的节点,但它确实工作它不链接它只是分配内存任何建议的建议 感谢

0 个答案:

没有答案