Example #1
0
        public void Add(HuffmanNode node)
        {
            var n = nodes.First;

            while (n != null && n.Value.Freq < node.Freq)
            {
                n = n.Next;
            }
            if (n == null)
            {
                nodes.AddLast(node);
            }
            else
            {
                nodes.AddBefore(n, node);
            }
        }
Example #2
0
        public void Encode(HuffmanNodeList hnl)
        {
            while (hnl.Count > 1)
            {
                var arr   = hnl.PopTwo();
                var left  = arr[0];
                var right = arr[1];
                left.PathCode  = 0;
                right.PathCode = 1;
                var parent = new HuffmanNode(left.Freq + right.Freq, left, right);
                left.Parent  = parent;
                right.Parent = parent;
                hnl.Add(parent);
            }
            Root = hnl.GetFirst();

            for (int i = 0; i < hnl.Leaves.Length; i++)
            {
                var node = hnl.Leaves[i];
                var key  = node.Word;
                var cs   = new List <char>();
                while (node.Parent != null)
                {
                    cs.Add(node.PathCode == 0 ? '0' : '1');
                    node = node.Parent;
                }
                var chars = new char[cs.Count];
                for (int j = cs.Count - 1; j >= 0; j--)
                {
                    chars[cs.Count - 1 - j] = cs[j];
                }
                var code = new string(chars);
                table[key]    = code;
                reTable[code] = key;
            }
        }
Example #3
0
 public HuffmanNode(int freq, HuffmanNode left, HuffmanNode right)
 {
     Freq  = freq;
     Left  = left;
     Right = right;
 }