C中的优先级队列链表实现 - enqueue()操作失败

时间:2017-03-12 13:18:41

标签: c pointers linked-list queue priority-queue

将节点正确插入队列的enqueue()操作包含我的程序的核心逻辑。我使用递归实现了相同的优先级队列,我知道程序的其余部分工作正常。现在我想使用常见迭代实现优先级队列。 enqueue()操作应该按照我的草案计划进行。

enter image description here

然而,当我运行程序时它失败了,没有任何错误(在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");
}

1 个答案:

答案 0 :(得分:1)

我认为问题出现在第一个Enqueue中(当PQ为空时),在这种情况下,您应该在第一个入队后更改PQ->headNode = newNode而不是prevnode->link = newNode我认为您的代码可以正常工作。

if(prevNode == NULL)
{
    PQ->headNode = newNode;
}
else
{
    prevNode->link = newNode;
}
相关问题