public string Dequeue() { if (length > 0) { if (length > 1) { string frontName = front.next.name; Node cur = rear.next; while (cur.next != front.next) { cur = cur.next; } front = new Node(); cur.next = null; front.next = cur; cur = null; length--; return frontName; } else { string frontName = front.next.name; front.next = null; rear.next = null; length--; return frontName; } } else { return ""; } }
public void BuildTree() { LeefDectionry.Clear(); for (int i = 0; i < 256; i++) { if (Frequencies[i] > 0) { Queue.Enqueue(new Node { Symbol = (char)i, Frequency = Frequencies[i], ISLeaf = true }); //LeefDectionry.Add((char)i, new Node { Symbol = (char)i, Frequency = Frequencies[i], ISLeaf =true }); } } while (Queue.Count() > 1) { var node1 = Queue.Dequeue(); var node2 = Queue.Dequeue(); var parent = new Node() { Symbol = '*', Frequency = node1.Frequency + node2.Frequency, Left = node1, Right = node2, ISLeaf = false, }; node1.Parent = node2.Parent = parent; node1.Bit = false; node2.Bit = true; if (node1.ISLeaf) LeefDectionry.Add(node1.Symbol,node1); if (node2.ISLeaf) LeefDectionry.Add(node2.Symbol, node2); Queue.Enqueue(parent); } Root = Queue.Dequeue(); int height = GetHight(Root); int arraySize = (int)Math.Pow(2, height); TreeArray = new short[arraySize]; for (int i = 0; i < arraySize; i++) { TreeArray[i] = -1; } this.SaveToArray(0, Root); }
public bool Enqueue(string name, Priority priority) { Node node = new Node(); node.name = name; node.priority = priority; if (length == 0) { front.next = node; rear.next = node; } else { if (node.priority > rear.next.priority) { Node cur = rear.next; while (cur.next != null && node.priority > cur.next.priority) { cur = cur.next; } if (cur.next == null) //we've reached the front { cur.next = node; front.next = node; } else { node.next = cur.next; cur.next = node; } } else { node.next = rear.next; rear.next = node; } } length++; return true; }
public PriorityQueue() { front = new Node(); rear = new Node(); length = 0; }
private void SaveToArray(int index, Node root) { TreeArray[index] = (short)root.Symbol; if (IsLeaf(root)) return; SaveToArray(2 * index + 1, root.Left); SaveToArray(2 * index + 2, root.Right); }
private int GetHight(Node node) { if (IsLeaf(node)) return 1; return 1 + Math.Max(GetHight(node.Left), GetHight(node.Right)); }
public bool IsLeaf(Node node) { return (node.Left == null && node.Right == null); }