55 lines
1.3 KiB
C++
55 lines
1.3 KiB
C++
#include <list>
|
|
#include <stack>
|
|
class HuffmanCode{
|
|
public:
|
|
explicit HuffmanCode(char *base){init(base);}
|
|
void init(char* base);
|
|
char* encode(char *in);
|
|
char* decode(char *in);
|
|
private:
|
|
struct codeTable{
|
|
char code;
|
|
bool* coding;
|
|
};
|
|
struct BiNode{
|
|
char code;
|
|
int power;
|
|
bool* coding;
|
|
BiNode lchild;
|
|
BiNode rchild;
|
|
bool operator<(BiNode& in){return this->power < in.power;}
|
|
};
|
|
BiNode* BiHead = nullptr;
|
|
std::list<BiNode> BiList;
|
|
std::list<codeTable> CodeTableList;
|
|
//void freeTheTree(BiNode* inHead);
|
|
};
|
|
void HuffmanCode::init(char *base) {
|
|
do{
|
|
for (auto &i : BiList) {
|
|
if(i.code == *base){
|
|
i.power++;
|
|
goto goOut;
|
|
}
|
|
}
|
|
BiList.push_back(BiNode{*base,0});
|
|
goOut:;
|
|
}while (*(++base));
|
|
std::list<BiNode> copy(BiList);
|
|
while (BiList.size() > 1){
|
|
BiList.sort();
|
|
BiNode L = *BiList.begin();
|
|
BiList.pop_front();
|
|
BiNode R = *BiList.begin();
|
|
BiList.pop_front();
|
|
BiList.push_back(BiNode{0,L.power+R.power, nullptr,L,R});
|
|
}
|
|
BiHead = &*BiList.begin();
|
|
std::stack<BiNode*> S;
|
|
S.push(BiHead);
|
|
while (!S.empty()){
|
|
BiNode* tmp = S.top();
|
|
S.pop();
|
|
if(tmp->rchild||tmp->lchild)
|
|
}
|
|
} |