我正在實施一個使用優先隊列的火車登機系統。我有工作代碼,但我需要做出以下更改。如何在C++中實現優先級隊列?
優先級別爲:高,中和低。所以乘客應該輸入他/她的名字和優先級。火車可以有多達30名乘客。 最後,我會相應地對乘客進行排序......在這裏,我到目前爲止我的問題是以字符串作爲參數,而不是現在的整數。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;
#define High 1
#define Medium 2
#define Low 3
/*
* Node Declaration
*/
struct node
{
int priority;
int info;
struct node *link;
};
/*
* Class Priority Queue
*/
class Priority_Queue
{
private:
node *front;
public:
Priority_Queue()
{
front = NULL;
}
/*
* Insert into Priority Queue
*/
void insert(int item, int priority)
{
node *tmp, *q;
tmp = new node;
tmp->info = item;
tmp->priority = priority;
if (front == NULL || priority < front->priority)
{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while (q->link != NULL && q->link->priority <= priority)
q = q->link;
tmp->link = q->link;
q->link = tmp;
}
}
/*
* Delete from Priority Queue
*/
void del()
{
node *tmp;
if (front == NULL)
cout << "Queue Underflow\n";
else
{
tmp = front;
cout << "Deleted item is: " << tmp->info << endl;
front = front->link;
free(tmp);
}
}
/*
* Print Priority Queue
*/
void display()
{
node *ptr;
ptr = front;
if (front == NULL)
cout << "Queue is empty\n";
else
{
cout << "Queue is :\n";
cout << "Priority Item\n";
while (ptr != NULL)
{
cout << ptr->priority << " " << ptr->info << endl;
ptr = ptr->link;
}
}
}
};
/*
* Main
*/
int main()
{
int choice, item, priority;
Priority_Queue pq;
do
{
cout << "1.Insert\n";
cout << "2.Delete\n";
cout << "3.Display\n";
cout << "4.Quit\n";
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Input the item value to be added in the queue : ";
cin >> item;
cout << "Enter its priority : ";
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default:
cout << "Wrong choice\n";
}
} while (choice != 4);
return 0;
}
你爲什麼不使用['std :: priority_queue'](http://www.cplusplus.com/reference/queue/priority_queue/)? –
你能明確指出你是否必須自己實現它嗎?否則解決方案將是使用標準庫。 – juanchopanza
我實際上可以使用任何數據結構,但我認爲這是方法 –