【发布时间】:2013-11-06 15:48:58
【问题描述】:
我正在实现 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
【问题讨论】:
-
嘿,抱歉,我刚刚在这里添加了我正在寻找的内容,谢谢!
-
但是你已经写了一些代码。那怎么了?
-
是什么让你得出结论,你的逻辑不正确?那是行不通的?它做什么,您对为什么有任何怀疑吗?您可以做的一件事来清理一些混乱是意识到您总是要添加一个节点,所以将它分配在函数开头的 one 位置,然后函数的其余部分可以专门用于查找将其插入的位置。
-
不相关:您的
Node结构类型-decl 缺少关键字typedef。它所做的只是声明一个名为Node的变量。并且queueStruct缺少类似的声明类型定义,如果它要在您呈现的代码中使用,如图所示。编写时它用作指针类型,但类型定义为结构类型,因此所有->用法甚至都无法编译。 -
嗨 Craig,添加最后一个值后程序挂起。我编辑了原始帖子以显示这一点。
标签: c linked-list queue