Possible Duplicate:
C implementation of skew heap
I have the following struct:
typedef struct Task_t {
float length;
int value;
} task_t;
I’m trying to use a skew heap to hold bunch of these structs using the ‘value’. So the struct with the lowest ‘value’ will be the root. My skew heap implementation follows:
typedef struct node
{
int value;
struct node * root;
struct node * leftchild;
struct node * rightchild;
} Node;
typedef Node * skewHeap;
struct skewHeap
{
struct node * root;
};
void skewHeapInit (struct skewHeap *sk)
{
sk->root = 0;
}
void skewHeapAdd (struct skewHeap *sk)
{
struct node *n = (struct node *) malloc(sizeof(struct node));
struct node *s;
assert(n != 0);
n->value = 0;
n->leftchild = 0;
n->rightchild = 0;
s->root = skewHeapMerge(s->root,n);
}
void skewHeapRemoveFirst (struct skewHeap *sk)
{
struct node * n = sk->root;
sk->root = skewHeapMerge(n->leftchild, n->rightchild);
free(n);
}
struct node * skewHeapMerge(struct node *left, struct node *right)
{
struct node *temp;
if (left == NULL)
return right;
if (right == NULL)
return left;
if (left->value < right->value)
{
temp = left->leftchild;
left->leftchild = skewHeapMerge(left->rightchild, right);
left->rightchild = temp;
return left;
}
else
{
temp = right->rightchild;
right->rightchild = skewHeapMerge(right->leftchild, left);
right->leftchild = temp;
return right;
}
}
My problem is I don’t know how to correctly insert and delete structs from this skew heap. Thanks in advance.
Instead of storing
valuedirectly in each node in your heap, store a pointer to a task instead. Your insertion method should take a pointer to the task you want to add. It will need to allocate memory for the task in the node, and then copy the relevant data in. You will need to free this in the removal method.E.g.
To be honest, you could just store
Task_t task;instead of using a pointer because it only contains an int and a float so copying it is not very expensive, but more generally you should use a pointer to a task. In your case, you would also be wasting even more memory by storing an actual struct instead of a pointer to a struct since you have an explicit root pointer in each node. I highly recommend getting rid of that regardless (it is inelegant as well as totally unnecessary), but that would require rewriting a fair bit of your code.