-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.hpp
More file actions
81 lines (73 loc) · 1.79 KB
/
Heap.hpp
File metadata and controls
81 lines (73 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef HEAP_H
#define HEAP_H
#include <cstdio>
#include <cstdlib>
#include <iostream>
//小根堆实现
template <class T>
class Heap {
private:
size_t heapLength , lastPos;
T *heapNode ;
public:
Heap():heapLength(1) , lastPos(1){
heapNode = (T*)malloc(sizeof(T));
}
~Heap() {
free(heapNode);
}
//输出堆内容
void print() ;
//判断堆是否为空
bool empty();
//输出堆顶的元素
T top() ;
//把一个节点放入堆中
void push(T node);
//删除堆顶元素
void pop() ;
};
template<class T>
void Heap<T>::print() {
printf("lastPos : %d \n" ,lastPos);
for(int i = 1 ; i < lastPos ; i++) {
printf("%d " ,heapNode[i]);
}printf("\n");
}
template<class T>
bool Heap<T>::empty() {
return (lastPos == 1);
}
template<class T>
T Heap<T>::top() {
return heapNode[1];
}
template<class T>
void Heap<T>:: push(T node) {
if(heapLength == lastPos) {
try {
heapLength <<= 1;
heapNode = (T*)realloc(heapNode , sizeof(T) *heapLength);
}
catch(const std::bad_alloc& e) {
std::cerr << e.what() << '\n';
}
}
heapNode[lastPos++] = node;
for(int nowPos = lastPos-1; nowPos > 1 ;){
if(heapNode[nowPos] < heapNode[nowPos >> 1])
std::swap(heapNode[nowPos] , heapNode[nowPos >> 1]) , nowPos >>= 1;
else break;
}
}
template<class T>
void Heap<T>::pop() {
std::swap(heapNode[--lastPos] , heapNode[1]);
for(int nowPos = 1 ; nowPos <<= 1 ; ) {
if( nowPos+1 < lastPos && heapNode[nowPos+1] < heapNode[nowPos] ) nowPos++;
if( nowPos < lastPos && heapNode[nowPos] < heapNode[nowPos >> 1])
std::swap(heapNode[nowPos >> 1] , heapNode[nowPos]);
else break;
}
}
#endif