一天一点数据结构+算法:复习堆的知识
这个代码还是有些问题,应该出在了堆头文件的保护#ifdef上。
大顶堆:
1 #ifdef _MAXHEAP_H_ 2 #define _MAXHEAP_H_ 3 4 template <class T> 5 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 <class T> 29 MaxHeap<T>::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 <class T> 39 MaxHeap<T>::~MaxHeap() 40 { 41 42 delete[] heapArray; 43 } 44 45 template <class T> 46 bool MaxHeap<T>::IsEmpty() 47 { 48 49 return currentSize == 0; 50 } 51 52 template <class T> 53 void MasHeap<T>::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<class T> 64 void MaxHeap<T>::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<class T> 82 const T& MaxHeap<T>::Top() const 83 { 84 85 return heapArray[0]; 86 } 87 88 89 template <class T> 90 void MaxHeap<T>::Pop() 91 { 92 //删除根节点,把最后一个节点拿过来。currentSize指向最后一个空位,只有减1之后才会向前找到真正的最后一个 93 heapArray[0] = heapArray[--currentSize]; 94 trickleDown(0); 95 } 96 97 98 99 template <class T> 100 void MaxHeap<T>::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 else 114 largerChild = leftChild; 115 116 if(top >= heapArray[largerChild]) 117 break; 118 else 119 //把儿子上移 120 heapArray[index] = heapArray[largerChild]; 121 index= largerChild; 122 123 } 124 125 heapArray[index] = top;//临时的根渗透在index放下 126 } 127 128 #endif