'How to reorder a pointer based skew heap from max-heap to min-heap or vice versa and with a new priority for each node?
After setting the new priority function and heap type, I need to reorder the current skew heap according to the new settings inside this setter method by calling the reorder function. I've already have the helper and main methods for merging nodes/queues. How should I implement this function?
The priority function just returns the integer priority of the data.
class Node {
public:
friend class PQueue;
Node(Data data) {
m_data = data;
m_right = nullptr;
m_left = nullptr;
}
Post getData() const { return m_data; }
private:
Data m_data; // data
Node* m_right; // right child
Node* m_left; // left child
};
class PQueue {
...
Node* m_heap;
...
void setPriorityFn(prifn_t priFn, HEAPTYPE heapType);
...
void reorder(Node* node); // Helper reorder function
};
Node* PQueue::merge(Node* p1, Node* p2) {
if (p1 == nullptr)
return p2;
else if (p2 == nullptr)
return p1;
if ((m_priorFunc(p1->m_post) < m_priorFunc(p2->m_post)) && m_heapType == MAXHEAP)
std::swap(p1, p2);
else if ((m_priorFunc(p1->m_post) > m_priorFunc(p2->m_post)) && m_heapType == MINHEAP)
std::swap(p1, p2);
std::swap(p1->m_left, p1->m_right);
p1->m_left = merge(p2, p1->m_left);
return p1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
