LZW编码算法的步骤如下:
步骤1:将词典初始化为包含所有可能的单字符,当前前缀P初始化为空。
步骤2:当前字符C=字符流中的下一个字符。
步骤3:判断P+C是否在词典中
(1)如果“是”,则用C扩展P,即让P=P+C,返回到步骤2。
(2)如果“否”,则输出与当前前缀P相对应的码字W;将P+C添加到词典中;令P=C,并返回到步骤2
数字查找树
节点结构体:
struct {
int suffix;
int parent, firstchild, nextsibling;
} node
初始化:
void InitDictionary( void){
int i;
for( i=0; i<256; i++){
dictionary[i].suffix = i; // 每一个ASCII字符
dictionary[i].parent = -1; // 因为是第一级节点,所以没有上级节点
dictionary[i].firstchild = -1; // 还没有添加子节点
dictionary[i].nextsibling = i+1; // 右侧相邻的子节点
}
dictionary[255].nextsibling = -1; // 最后一个ASCII字符,第一级的最后一个节点,没有下一个相邻的节点了
next_code = 256; // 新节点会一次放到dictionary列表的后面
}
向数字查找树中添加新节点:
void AddToDictionary( int character, int string_code){ // 把character挂到string_code后面
int firstsibling, nextsibling;
if( 0>string_code) return; // string_code不合法
dictionary[next_code].suffix = character; // 把新节点放入词典中,
dictionary[next_code].parent = string_code; // 父节点是string_code
dictionary[next_code].nextsibling = -1; // 先不考虑邻居
dictionary[next_code].firstchild = -1; // 没有子节点
firstsibling = dictionary[string_code].firstchild; // 查找string_code下已经挂了哪些节点,要把character放在他们后面
if( -1<firstsibling){ // the parent has child string_code下还有其他节点,找到当前的最后一个节点
nextsibling = firstsibling; // 从第一个结点开始,找它的邻居
while( -1<dictionary[nextsibling].nextsibling ) // 一直找到最后一个邻居