1 #ifndef dsa_MergeableHeap_H__
2 #define dsa_MergeableHeap_H__
29 template<
class Element>
37 Node(Element
const& value):
38 value_(value), lChild_(NULL), rChild_(NULL), weight_(1){
44 void clear(Node* node) {
51 Node* dup(Node* node) {
52 if (node == NULL)
return NULL;
53 Node* ret =
new Node(node->value_);
54 ret->lChild_ = dup(node->lChild_);
55 ret->rChild_ = dup(node->rChild_);
57 ret->weight_ += (ret->lChild_ == NULL ? 0 : ret->lChild_->weight_);
58 ret->weight_ += (ret->rChild_ == NULL ? 0 : ret->rChild_->weight_);
61 Node* merge(Node* left, Node* right) {
62 if (left == NULL)
return right;
63 if (right == NULL)
return left;
64 if (left->value_ < right->value_) {
65 std::swap(left, right);
67 left->rChild_ = merge(left->rChild_, right);
68 size_t lw = (left->lChild_ == NULL ? 0 : left->lChild_->weight_);
69 size_t rw = (left->rChild_ == NULL ? 0 : left->rChild_->weight_);
71 std::swap(left->lChild_, left->rChild_);
73 left->weight_ = 1 + lw + rw;
93 root_ = dup(heap2.root_);
102 heap2->root_ = root_;
109 Element
const&
top()
const {
110 return root_->value_;
117 return (root_ == NULL ? 0 : root_->weight_);
124 return (
size() == 0);
130 void push(Element
const& value) {
131 root_ = merge(root_,
new Node(value));
138 Node* l = root_->lChild_;
139 Node* r = root_->rChild_;
156 root_ = merge(root_, heap2->root_);
168 #endif // dsa_MergeableHeap_H__
void push(Element const &value)
加入element
Element const & top() const
回傳最大的那個 Element
MergeableHeap & copyFrom(MergeableHeap const &heap2)
複製資料
MergeableHeap()
constructor
一個用 左偏樹 實作的 Maximum-Heap , 除了原本heap有的功能外, 還支援 merge 功能
size_t size() const
回傳資料個數
~MergeableHeap()
destructor
MergeableHeap & operator=(MergeableHeap const &heap2)
same as copyFrom(heap2)
void merge(MergeableHeap *heap2)
void moveTo(MergeableHeap *heap2)
將自己的資料丟給指定的heap, 從此自己一身空
bool empty() const
回傳是否為空
MergeableHeap(MergeableHeap const &heap2)
constructor, 並且複製資料