斜堆。
测试文件 main.cpp:
#include#include "SkewHeap.h" using std::cout; using std::endl; int main() { SkewHeap<int> lh(SkewHeap<int>::HeapType::MINIMEM); auto il = { 1,2,3,4,5,5,6,7,8,9 }; for (auto& x : il) lh.push(x); cout <<"Element: "; lh.levelTraversal(); cout < endl; cout <<"Pop: " < endl; lh.pop(); cout <<"Element: "; lh.levelTraversal(); cout << endl; return 0; }
头文件 "SkewHeap":
#pragma once #ifndef __SKEWHEAP_H__ #define __SKEWHEAP_H__ #include "BinaryTreeOperations.h" templateclass SkewHeap { struct Node { _Ty key; Node* left = nullptr; Node* right = nullptr; Node(const _Ty& _key) :key(_key) {} }; public: enum class HeapType :bool { MINIMEM = 0, MAXIMEM }; public: SkewHeap() = default; SkewHeap(HeapType _heapType) { heapType = _heapType; } ~SkewHeap() { BTO::clear(root); size_n = 0; } void clear() noexcept { BTO::clear(root); size_n = 0; } void preorderTraversal() { BTO::preorderTraversal(root, drawData); } void inorderTraversal() { BTO::inorderTraversal(root, drawData); } void postorderTraversal() { BTO::postorderTraversal(root, drawData); } void iterativePreorderTraversal() { BTO::iterativePreorderTraversal(root, drawData); } void iterativeInorderTraversal() { BTO::iterativeInorderTraversal(root, drawData); } void iterativePostorderTraversal() { BTO::iterativePostorderTraversal(root, drawData); } void levelTraversal() { BTO::levelTraversal(root, drawData); } size_t size() const { return size_n; } void pop(); _Ty& top() const; void push(const _Ty&); void merge(SkewHeap<_Ty>&); private: static void drawData(const Node* _node) { std::cout <<_node->key <<" "; } bool compare(const _Ty& _a, const _Ty& _b) { return (heapType == HeapType::MAXIMEM) ? (_a > _b) : (_a < _b); } Node* merge(Node*&, Node*&); private: Node* root = nullptr; size_t size_n = 0; HeapType heapType = HeapType::MAXIMEM; }; template void SkewHeap<_Ty>::pop() { if (root == nullptr) throw std::exception("SkewHeap is empty!"); Node* leftT = root->left; Node* rightT = root->right; delete root; root = merge(leftT, rightT); --size_n; } template _Ty& SkewHeap<_Ty>::top() const { if (root == nullptr) throw std::exception("SkewHeap is empty!"); return root->key; } template void SkewHeap<_Ty>::push(const _Ty& _key) { Node* temp = new Node(_key); root = merge(root, temp); temp = nullptr; ++size_n; } template void SkewHeap<_Ty>::merge(SkewHeap<_Ty>& _lh) { if (heapType != _lh.heapType) throw std::exception("Bad heapType"); root = merge(root, _lh.root); _lh.root = nullptr; size_n += _lh.size_n; _lh.size_n = 0; } template typename SkewHeap<_Ty>::Node* SkewHeap<_Ty>::merge(Node*& _n1, Node*& _n2) { if (_n1 == nullptr && _n2 == nullptr) return nullptr; else if (_n1 == nullptr) return _n2; else if (_n2 == nullptr) return _n1; if (!compare(_n1->key, _n2->key)) std::swap(_n1, _n2); _n1->right = merge(_n1->right, _n2); std::swap(_n1->left, _n1->right); return _n1; } #endif // !__SKEWHEAP_H__