private void BuildTree() { if (q1 == null || q1.Count == 0) { return; } if (q1.Count == 1 && q2.Count == 0) { q2.AddFirst(q1.First()); q1.RemoveFirst(); return; } while (true) { if (q1.Count == 0 && q2.Count == 1) { return; } TwoNodes twoNodes = GetTwoNodes(); HuffmanNode newNode = new HuffmanNode('*', Math.Round(twoNodes.node1.weight + twoNodes.node2.weight, 3)); newNode.right = twoNodes.node1.weight < twoNodes.node2.weight ? twoNodes.node1 : twoNodes.node2; newNode.left = twoNodes.node1.weight < twoNodes.node2.weight ? twoNodes.node2 : twoNodes.node1; q2.AddLast(newNode); } }
private TwoNodes GetTwoNodes() { TwoNodes item = new TwoNodes(); LinkedListNode <HuffmanNode> node1, node2, node3, node4; node1 = Peek(q1, 0); node2 = Peek(q1, 1); node3 = Peek(q2, 0); node4 = Peek(q2, 1); LinkedListNode <HuffmanNode>[] arr = new LinkedListNode <HuffmanNode>[4] { node1, node2, node3, node4 }; Array.Sort(arr, (a, b) => { if (a == null && b == null) { return(1); } else if (a == null && b != null) { return(1); } else if (a != null && b == null) { return(-1); } else { return(a.Value.weight.CompareTo(b.Value.weight)); } }); int q1c = 0, q2c = 0; if (arr[0].List == q1) { item.node1 = q1.ElementAt(q1c); q1c++; } else { item.node1 = q2.ElementAt(q2c); q2c++; } if (arr[1].List == q1) { item.node2 = q1.ElementAt(q1c); q1c++; } else { item.node2 = q2.ElementAt(q2c); q2c++; } while (q1c > 0) { q1c--; q1.RemoveFirst(); } while (q2c > 0) { q2c--; q2.RemoveFirst(); } return(item); }