我已经通过去为一个节点分配了一个编码类中的地址
newnode.zero = &zeronode;
newnode 和 zeronode 是节点结构的实例,它有一个成员指针 Node *zero。如何在同一类的不同函数中访问该节点?目前我似乎只能得到一个指针——通过
Node newnode = *root.zero;
这是现在的整个编码类;
/**
* File: encoding.cpp
* ------------------
* Place your Encoding class implementation here.
*/
#include "encoding.h"
#include "map.h"
#include "string.h"
#include <string>
#include "strlib.h"
#include "huffman-types.h"
#include "pqueue.h"
using namespace std;
Encoding::Encoding() {
}
Encoding::~Encoding() {
frequencyTable.clear();
}
void Encoding::compress(ibstream& infile, obstream& outfile) {
getFrequency(infile);
compresskey = "";
foreach(ext_char key in frequencyTable) {
int freq = frequencyTable.get(key);
Node newnode;
newnode.character = key;
newnode.weight = freq;
newnode.zero = NULL;
newnode.one = NULL;
huffqueue.enqueue(newnode, freq);
string keystring = integerToString(key);
string valstring = integerToString(freq);
compresskey = compresskey + "Key = " + keystring + " " + "Freq = " + valstring + " ";
}
buildTree();
createReferenceTable();
}
void Encoding::decompress(ibstream& infile, obstream& outfile) {
}
void Encoding::getFrequency(ibstream& infile) {
int ch;
while((ch = infile.get()) != EOF){
if(frequencyTable.containsKey(ch)){
int count;
count = frequencyTable.get(ch);
frequencyTable[ch] = ++count;
}
else {
frequencyTable.put(ch, 1);
}
}
frequencyTable.put(PSEUDO_EOF, 1);
}
void Encoding::buildTree() {
int numnodes = huffqueue.size();
for (int i = 1; i < numnodes; i++) {
Node newnode;
newnode.character = NOT_A_CHAR;
Node zeronode = huffqueue.extractMin();
newnode.zero = &zeronode;
Node onenode = huffqueue.extractMin();
newnode.one = &onenode;
int newfreq = zeronode.weight + onenode.weight;
newnode.weight = newfreq;
huffqueue.enqueue(newnode, newfreq);
}
}
void Encoding::createReferenceTable() {
Node root = huffqueue.extractMin();
string path = "";
tracePaths(root, path);
}
void Encoding::tracePaths(Node root, string path) {
if (!root.character == NOT_A_CHAR) {
ext_char ch = root.character;
referenceTable.put(ch, path);
return;
}
for (int i = 0; i < 2; i++) {
if (i == 0) {
if (root.zero != NULL) {
Node newnode = root->zero;// This is where the problem is
path = path + "0";
tracePaths(newnode, path);
}
}
else if (i == 1) {
if (root.one != NULL) {
Node newnode = root.one;
path = path + "1";
tracePaths(newnode, path);
}
}
}
return;
}