QueueADT の単一リンク リスト バージョンを実装しています。キューの作成時に、クライアントが比較機能を提供する場合、新しいデータをキューに挿入するときにそれを使用します。クライアントが比較機能を提供しない場合は、標準のキュー挿入を使用して、キューの最後に挿入します。
比較関数を使用して挿入するロジックに問題があります。比較関数が返すものしかわかりません。
compare( void*a, void*b)
//compare returns < 0 if a < b
//compare returns = 0 if a == b
//compare returns > 0 if a > b
標準のキューとリンクされたノード構造があります。
typedef struct queueStruct {
Node *front;
Node *rear;
int count;
int (*compare)(const void*, const void*);
};
typedef struct Node {
void* value;
struct Node *next;
}Node;
そして、これが挿入機能での私の試みです。ロジックが正しいとは思わないので、洞察や疑似コードをいただければ幸いです。
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;
}
}
}
}
テスト:
次のデータをキューに挿入しようとすると:
42, 17, -12, 9982, 476, 2912, -22, 3291213, 7782
これらの値を挿入すると、最後の値まで機能するようです。プログラムは次の場所でハングします
inserting 7782
Greater than 0
Greater than 0
Greater than 0
Greater than 0