这个代码还是有些问题,应该出在了堆头文件的保护#ifdef上。
大顶堆:
1 #ifdef _MAXHEAP_H_ 2 #define _MAXHEAP_H_ 3 4 template5 class MaxHeap 6 { 7 8 public: 9 MaxHeap(int mx = 10); 10 virtual ~MaxHeap(); 11 12 bool IsEmpty(); 13 void Push(const T&); 14 void Pop(); 15 const T& Top() const; 16 17 private: 18 T* heapArray; 19 int maxSize; 20 int currentSize; 21 22 void trickleUp(int index); 23 void trickleDown(int index); 24 25 }; 26 27 28 template 29 MaxHeap ::MaxHeap(int mx = 10) 30 { 31 32 if(mx<1) throw "max size must be >=1"; 33 maxSize = mx; 34 currentSize = 0; 35 heapArray = new T[maxSize]; 36 } 37 38 template 39 MaxHeap ::~MaxHeap() 40 { 41 42 delete[] heapArray; 43 } 44 45 template 46 bool MaxHeap ::IsEmpty() 47 { 48 49 return currentSize == 0; 50 } 51 52 template 53 void MasHeap ::Push(const T& e) 54 { 55 56 if(currentSize == maxSize) throw "MaxHeap is full."; 57 58 heapArray[currentSize] = e; 59 trickleUp(currentSize++); 60 61 } 62 63 template 64 void MaxHeap ::trickleUp(int index) 65 { 66 int parent = (index-1)/2; 67 T bottom = heapArray[index];//用临时变量先保存 68 while(index > 0 && heapArray[parent] < bottom) 69 { 70 71 heapArray[index] = heapArray[parent]; 72 index = parent; 73 parent = (parent - 1) /2 ; 74 75 } 76 heapArray[index] = bottom; 77 78 79 } 80 81 template 82 const T& MaxHeap ::Top() const 83 { 84 85 return heapArray[0]; 86 } 87 88 89 template 90 void MaxHeap ::Pop() 91 { 92 //删除根节点,把最后一个节点拿过来。currentSize指向最后一个空位,只有减1之后才会向前找到真正的最后一个 93 heapArray[0] = heapArray[--currentSize]; 94 trickleDown(0); 95 } 96 97 98 99 template 100 void MaxHeap ::trickleDown(int index)101 {102 int largerChild;103 T top = heapArray[index];//临时的根104 105 //每次都是删除根节点,currentSize到最后一层的上一层106 while(index < currentSize/2)107 {108 //计算节点左儿子和右儿子的序号109 int leftChild = 2 * index + 1;110 int rightChild = leftChild + 1;111 if(rightChild < currentSize && heapArray[leftChild] < heapArray[rightChild])112 largerChild = rightChild;113 else114 largerChild = leftChild;115 116 if(top >= heapArray[largerChild])117 break;118 else119 //把儿子上移120 heapArray[index] = heapArray[largerChild];121 index= largerChild;122 123 }124 125 heapArray[index] = top;//临时的根渗透在index放下126 }127 128 #endif