1. 程式人生 > >資料結構實習之Huffman編譯碼器(三)

資料結構實習之Huffman編譯碼器(三)

3.對每個字元編碼:

void HuffanTree::enCode(int n,CListCtrl *list)//huffman coding
{
	HuffmanNode *current;
	HuffmanNode *parent;
	CString code="";//編碼
	int charNum,nodeNum;
	char ch;

	for(charNum=0;charNum<n;charNum++)
	{
		code="";
		ch= list->GetItemText(charNum,0)[0];
		for(nodeNum=0;nodeNum<n;nodeNum++)
		{
			if (ch==huffNode[nodeNum]->character)
			{
				current=huffNode[nodeNum]->sAddress;
				parent=current->parent;
				while(current!=root)
				{
					if (parent!=NULL&&parent->rightChild->sAddress==current->sAddress)
						code+="1";
					if (parent!=NULL&&parent->leftChild->sAddress==current->sAddress)
						code+="0";
					current=parent;
					parent=current->parent;
				}
				code.MakeReverse();
				huffNode[nodeNum]->hfmCode=code;//將code逆序
			}
		}
		list->SetItemText(charNum,3,code);
	}
	
}


4.對字串編譯碼

void CHuffmanDlg::OnButtonDecode() 
{
	// TODO: Add your control notification handler code here
	CString codeStr,str,strTemp,strTemp2;
	CString decodeStr="";
	GetDlgItemText(IDC_EDIT_CODE,codeStr);
	str=codeStr;
	int n=m_num;//葉子節點個數
	int i=0,j=0;
	int minLC=m_plist.GetItemText(0,3).GetLength(),maxLC=0;//最短和最長哈弗曼碼
	int len=0;
	for (i=0;i<n;i++)
	{
		len=m_plist.GetItemText(i,3).GetLength();
		minLC=minLC<=len?minLC:len;
		maxLC=maxLC>=len?maxLC:len;
	}
	while(str!="")
	{
		for (i=minLC;i<=maxLC;i++)
		{
			strTemp=str.Left(i);
			j=0;
			strTemp2=m_plist.GetItemText(j,3);
			while(strTemp!=strTemp2&&j<n)
			{
				j++;
				strTemp2=m_plist.GetItemText(j,3);
			}
			if (strTemp==m_plist.GetItemText(j,3)&&j<n)
			{
				str=str.Right(str.GetLength()-i);
				decodeStr+=m_plist.GetItemText(j,0);
			}
		}
	}
	SetDlgItemText(IDC_EDIT_DECODE,decodeStr);
}