武汉工程大学计算机科学与工程学院 综合设计报告
min2 = listNode[j].weight; rchild = j; }
double w = listNode[lchild].weight + listNode[rchild].weight; HafumanNode newNode = new HafumanNode('#', w); newNode.lchild = lchild; newNode.rchild = rchild; listNode.Add(newNode);
HafumanNode templchild =listNode[lchild]; templchild.parent = i;
listNode[lchild] = templchild; HafumanNode temprchild = listNode[rchild]; temprchild.parent = i;
listNode[rchild] = temprchild; } }
上面这个函数主要是构造哈夫曼树,这个算法跟课本上的一模一样。有技巧,但没有难度。下面这个函数是根据构造好的哈夫曼树对各个字符求出它的哈夫曼编码,然后存放在字符数组中对应的位置。
public string[] CreateHCode() {
string str=\;
for (int i = 0; i < leaf; i++) {
str = \;
- - 9
武汉工程大学计算机科学与工程学院 综合设计报告
int f = listNode[i].parent; int c = i; while (f != -1) {
if (listNode[f].lchild == c) str += \; else
str += \; c = f;
f = listNode[f].parent; }
code[i] =ReverseString(str); }
return code; }
3.2.3 Form1类
这个Form1类看起来很不爽,因为它的名字是默认的,而没有按照匈牙利命名法来命名。这个类是主窗体类。下面列出了它的主要功能代码:
这个函数是编码,根据已经编码好的编码数组,查找各个字符的编码,然后把它连接起来,组成一个1和0的字符串,就是输入字符串的编码了。
private bool Code(string s,string [] str) {
char[] codestr = s.ToCharArray();
- 10 -
武汉工程大学计算机科学与工程学院 综合设计报告
richTextBox1.Text = \; string temp = \; int m = 0;
for (int i = 0; i < codestr.Length; i++) {
m = GetIndex(hafumantree.listNode, codestr[i]); if (m == -1) {
MessageBox.Show(\你?输?入?了?不?存?在ú的?编括?码?:\\n\+codestr[i].ToString());
return false ; }
temp += str[m]; }
这个主窗体还有个很重要的函数就是画树,以下是它的全部代码。 private void DrawTree(int n, Point point) {
int lchild=-1,rchild=-1;
Graphics g = Graphics.FromHwnd(pictureBox1.Handle); Pen pen = new Pen(Color.Red);
g.DrawEllipse(pen,point.X,point.Y,20,20); if (hafumantree.listNode[n].lchild != -1) {
lchild = hafumantree.listNode[n].lchild;
Point newPoint = new Point(point.X - 35, point.Y + 30); DrawTree(lchild, newPoint);
g.DrawLine(pen, new Point(point.X + 10, point.Y + 10), new Point(newPoint.X + 10, newPoint.Y + 10));
}
- - 11
武汉工程大学计算机科学与工程学院 综合设计报告
else {
Font font = new Font(\黑ú体?\,10);
Brush brush = new SolidBrush(Color.Green);
g.DrawString(hafumantree.listNode[n].data.ToString(), font, brush, point);
}
if (hafumantree.listNode[n].rchild != -1) {
rchild = hafumantree.listNode[n].rchild;
Point newPoint = new Point(point.X + 35, point.Y + 30); DrawTree(rchild, newPoint);
g.DrawLine(pen, new Point(point.X + 10, point.Y + 10), new Point(newPoint.X + 10, newPoint.Y + 10));
} else {
Font font = new Font(\黑ú体?\, 10); Brush brush = new SolidBrush(Color.Green);
g.DrawString(hafumantree.listNode[n].data.ToString(), font, brush, point);
} }
- 12 -
武汉工程大学计算机科学与工程学院 综合设计报告
第四章 设计结果及分析
4.1 程序运行结果
程序运行后的界面如图所示:
图 4.1 程序运行结果
输入字符串abcda,点击编码后输出正常,但是在解码框中输入110001101时就有问题了,如图所示,解码输出框中的字符串最后一个字符是#
- 13 -