每当我在程序中运行任何函数(插入并显示,由于无法插入而无法确定是否删除),我似乎总是收到“ Segmentation Error:11”。我不太确定这是什么意思,或者从哪里开始寻求修复。任何帮助将不胜感激从哪里开始。我了解到,这与内存有关,从我发现的情况来看,这可能意味着某件事占用了太多内存。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "priority_queue.h"
//#include <heap.h>
using namespace std;
struct node{
int priority;
int info;
struct node* link;
};
class PriorityQueue{
private:
node* front;
public:
void Priority_Queue(){
front = 0;
}
void insert(int item, int priority){
node* temp, *q;
temp = new node;
temp->info = item;
temp->priority = priority;
if(front == 0 || priority < front->priority){
temp ->link = front;
front = temp;
}
else{
q = front;
while(q->link != 0 && q->link->priority <= priority)
q = q->link;
temp->link = q->link;
q->link = temp;
}
}
void del(){
node* temp;
if(front == 0)
cout << "Underflow" << endl;
else{
temp = front;
cout << "Delete item is: " << temp->info << endl;
front = front->link;
free(temp);
}
}
void display(){
node* ptr;
ptr = front;
if(front == 0)
cout << "Queue is empty" << endl;
else{
cout << "Queue is: " << endl;
cout << "Priority Item" << endl;
while(ptr != 0){
cout << ptr->priority << endl;
ptr = ptr->link;
}
}
}
};
int main(){
int choice, item, priority;
PriorityQueue pq;
while(1){
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Quit" << endl;
cout << "Enter Choice " << endl;
cin >> choice;
switch(choice){
case 1:
cout << "Input the item value to be added into the queue" << endl;
cin >> item;
cout << "Enter its priority " << endl;
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default:
cout << "That is not an option" << endl;
}
}
//while(choice != 4);
return 0;
}
答案 0 :(得分:1)
问题似乎出在类定义上。正如WhozCraig指出的那样,假定构造函数的名称是错误的,因此它永远不会被调用。更正的代码:
class PriorityQueue {
private:
node* front;
public:
PriorityQueue() : front(nullptr) {
}
};
如果您查看调试器,可能会发现front
从未正确初始化。在C ++中,尝试使用nullptr
表示“空指针”。在C语言中使用NULL
。使用0
会产生很多歧义,即使它由于历史原因而“起作用”。