【发布时间】:2017-08-02 12:58:13
【问题描述】:
将节点正确插入队列的enqueue() 操作包含我程序的核心逻辑。我已经使用递归实现了相同的优先级队列,并且我知道程序的其余部分工作正常。现在我想使用通用迭代来实现优先级队列。 enqueue() 操作应该按照我下面的草稿计划工作。
但是当我运行程序时它失败了,根本没有任何错误(在 VS 和 gcc 中测试)。我只是不明白我的逻辑在哪里失败,这让我发疯。帮助将不胜感激!
代码如下。
// The PQ is sorted according to its value
// Descending order sorted insertion (bigger first -> smaller last)
void enqueue(pqType val, PriorityQueue *PQ)
{
if (!isFull(PQ)) {
PQ->count++;
Node *currentNode = PQ->headNode; // Iterate through PQ using currentNode
Node *prevNode = NULL; // the previous Node of our current iteration
Node *newNode = (Node*) malloc(sizeof(Node)); // The new Node that will be inserted into the Queue
int i = 0;
while (i < MAX_QUEUE_SIZE) {
// if PQ is empty, or if val is larger than the currentNode's value then insert the new Node before the currentNode
if ((currentNode == NULL) || (val >= currentNode->value)) {
newNode->value = val;
newNode->link = currentNode;
prevNode->link = newNode;
break;
}
else {
prevNode = currentNode;
currentNode = currentNode->link;
}
i++;
}
//free(currentNode);
//free(prevNode);
}
else
printf("Priority Queue is full.\n");
}
【问题讨论】:
-
在你的第一个队列(PQ 为空)这行“prevNode->link = newNode”应该失败
-
为什么是链表实现?对于优先级队列来说,堆通常是更好的选择。
标签: c pointers linked-list queue priority-queue