优先队列的插入和显示功能

priority queue INSERTION and DISPLAY function in C++

本文关键字:显示 功能 插入 优先队列      更新时间:2023-10-16

尝试实现优先级队列插入(dev c++ IDE),即在具有优先级的节点之前>新节点的优先级。来自用户的插入似乎发生在命令提示符上,但display函数只输出第一个节点。为什么没有显示其他队列元素?我担心它们没有首先被插入,这就是为什么在随后插入10、20、30,然后删除时,它打印空队列。因为队列只有10个人,为什么?请建议。

注意:我没有包括delete和main函数,这里的代码,但它在程序中,显然…没有运行时异常发生…编译工作正常。但是没有期望的输出。

#include<iostream>
using namespace std;
typedef struct node{ //template would enable generic datatype
        int info,prn;
        node * link;
}node;
node * start = 0;
int item,pri;

    void insert(int item, int pri){
     node * newnode = new node;
     newnode-> info = item;
     newnode-> prn = pri;
     if(start == 0){//explicit check in insert if start is NULL.
              start = newnode;
              newnode->link = 0;
     }
     /*When you first run the program, start = 0 or NULL. You then say prev = start, 
so as a result prev = NULL. So when you try to access prev->link, there's an access violation.*/
     else{ 
          node * prev= start;
          node * temp = prev->link;
          while (temp!= 0){
                if(temp->prn > newnode->prn){
                        newnode -> link = prev -> link;
                        prev -> link = newnode;
                break;
                } 
                else{
                     if( temp->link == 0){
                              temp -> link = newnode;
                              newnode->link = 0;
                     break;
                     }
                } 
           prev = prev->link;                    
          }
     }
}
void display(){
     if(start == 0)
              cout<<"Empty priority queuen";
     else{
          cout<<("The Contents of the List are: ");
          node *temp = start;   
          while(temp!=NULL){   //if we do while temp->link!=NULL, then last node won't print
                               cout<< temp->info;
                               cout<<" ---> ";
                               temp = temp->link;
          }
     }             
}

第一次调用insert时,start将为0,但是您将把它赋值给prev。在下一行,给出错误的代码调用prev->link,因此c++在调用NULL(调用未定义行为)上的方法时崩溃。如果start为NULL,则应该在insert中添加显式检查。

第一次运行程序时,start = 0或NULL。然后输入prev = start,因此prev = NULL。所以当你试图访问prev->link时,就会出现访问冲突