Assignment2
Assignment2
#include <unordered_map>
#include <cmath>
#include <climits>
#include <vector>
struct Node {
bool mark;
Node *parent;
Node *child;
Node *left;
Node *right;
//construt node
Node(int k) {
key = k;
degree = 0;
mark = false;
right=left = this;
};
class FibonacciHeap {
private:
Node* minNode; // Pointer to the minimum node
cout << "linking node of " << y->key << " under the node " << x->key << endl;
y->left->right = y->right;
y->right->left = y->left;
// Make y a child of x
y->parent = x;
y->left = y->right = y;
if (!x->child) {
x->child = y;
} else {
y->left = x->child;
x->child->right ->left = y;
x-> child->right = y;
x->degree = x->degree + 1;
y->mark = false;
}
// Helper: Consolidate trees after extract-min
void consolidate() {
vector<Node*> rootList;
if ( curr) {
do {
rootList.push_back(curr);
curr = curr->right;
Node* x = w;
int d = x->degree;
while (A[d]) {
Node* y = A[d];
cout << "Merging trees with same degree " << d << endl;
if (x->key > y->key) swap(x, y); // Ensure x has the smaller key
A[d] = nullptr;
d++;
A[d] = x;
minNode = nullptr;
for (Node* a : A) {
if (a) {
if (!minNode) {
a->left = a->right = a;
minNode = a;
} else {
a->left = minNode;
a->right = minNode->right;
minNode->right->left = a;
minNode->right = a;
public:
if (minNode !=nullptr) {
minNode = node;
} else {
node->left = minNode;
minNode->right = node;
nodeCount++;
int getMin() {
cout <<'\n';
void extractMin() {
if (!minNode) {
return;
Node* z = minNode;
cout << "Extracting minimum node: " << z->key << '\n';
if (z->child) {
cout << "adding childrn of node " << z->key << " to raot list" << endl;
Node* x = z->child;
do {
x->left->right = x->right;
x->right->left = x->left;
x->left = minNode;
x ->right = minNode->right;
minNode ->right->left = x;
minNode-> right = x;
x = next;
z->left->right = z->right;
z->right->left = z->left;
if (z == z->right) {
} else {
minNode = z->right;
consolidate();
nodeCount--;
delete z;
void print() {
if (!minNode) {
do {
};
int main() {
FibonacciHeap heap;
heap.insert(23);
heap.insert(17);
heap .insert(13);
heap.insert(27);
heap.insert(29);
heap.print();
heap.extractMin();
heap.print();
return 0;