简体   繁体   中英

Priority Queue linked list implementation in C - enqueue() operation failure

The enqueue() operation which properly inserts a Node into the queue contains the core logic of my program. I have implemented the same Priority Queue using recursion and i know that the rest of the program works fine. Now i want to implement the priority queue using common iteration. The enqueue() operation should work according to my draft plan below.

在此处输入图片说明

However when i run the program it fails, without any errors at all (tested in VS and gcc). I just cannot understand where my logic in this one fails and it is driving me nuts. Help will be appreciated!

The code follows.

// 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");
}

I think the problem is in the first Enqueue ( when PQ is empty), in this case you should change the PQ->headNode = newNode not prevnode->link = newNode , after the first enqueue I think your code will work fine.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM