I am implementing a single linked list version of a QueueADT. Upon Queue creation, if the client gives us a compare function, we are to use that on inserting new data into the queue. If the client does not provide a compare function, we use standard queue insertion and just insert to the back of the queue.
I am having trouble with the logic of using the compare function to insert. We only know what the compare function returns.
compare( void*a, void*b)
//compare returns < 0 if a < b
//compare returns = 0 if a == b
//compare returns > 0 if a > b
I have your standard queue and linked node structures:
typedef struct queueStruct {
Node *front;
Node *rear;
int count;
int (*compare)(const void*, const void*);
};
typedef struct Node {
void* value;
struct Node *next;
}Node;
And here is my attempt at the insert function. I don't think the logic is correct, and would appreciate some insight or maybe even pseudocode for this!
void que_insert(queueStruct queue, void *data){
//if the queue is empty
if (que_empty(queue)){
Node *node;
node = malloc(sizeof(Node));
node -> value = data;
node -> next = NULL;
queue->front = node;
queue->rear = node;
queue->count++;
}
else{
//if there is no comparison function, just use FIFO
if (queue->compare == NULL){
printf("Fifo\n");
Node *node;
node = malloc(sizeof(Node));
node->value = data;
node->next = NULL;
queue->rear->next = node;
queue->rear = node;
queue->count++;
}
else{
Node *temp;
temp = queue->front;
//if what we are adding is smaller than the head, then we found our new head
if (queue->compare(data, temp->value) < 0){
printf("Less Than 0\n");
Node *node;
node = malloc(sizeof(Node));
node->value = data;
node->next = queue->front;
queue->front = node;
queue->count++;
return;
}
while (temp->next != NULL){
if (queue->compare(data, temp->value)> 0){
printf("Greater than 0\n");
temp = temp->next;
}
else if (queue->compare(data, temp->value) == 0){
printf("Equals 0\n");
Node *node;
node = malloc(sizeof(Node));
node->value = data;
node->next = temp->next;
temp->next = node;
queue->count++;
return;
}
}
//temp should be at the rear
if (queue->compare(data, temp->value)> 0){
printf("Adding to rear");
Node *node;
node = malloc(sizeof(Node));
node->value = data;
node->next = NULL;
}
}
}
}
Testing:
Upon trying to insert the following data's into the queue:
42, 17, -12, 9982, 476, 2912, -22, 3291213, 7782
It seems that inserting these values works up until the last one, the program hangs at
inserting 7782
Greater than 0
Greater than 0
Greater than 0
Greater than 0