首页 > 技术文章 > C++ 之优先队列

linyuxuan 2020-04-13 15:29 原文

define maxSize 5

  typedef int typeData;

 typedef struct _QNode {
 int priority;
 typeData data;
 struct _QNode *next;
  }QNode;

 typedef struct _linkQN {
 int length;
 QNode *front; //队头指针 
 QNode *rear;  // 尾部指针
  }linkQN;

// 初始化队列
bool initLink(linkQN* list) {
if (!list) return false;
list->length = 0;
list->front = NULL;
list->rear = NULL;
return true;
}
//判断队列为空 
bool IsEmpty(linkQN* list) {
if (!list) return false;
if (list->rear == NULL) {
	cout << "队列为空" << endl;
	return true;
}
return false;
 }

 //判断队列是否为满 
 bool IsFull(linkQN* list) {
if (!list) return false;
if (list->length == maxSize) {
	cout << "队列已满" << endl;
	return true;
}
return false;
 }
 // 插入节点
 bool  EnterQueue(linkQN* list, typeData data, int priority) {
if (!list)return false;
if (IsFull(list)) {
	return false;
}
QNode *newNode = new QNode;
newNode->priority = priority;
newNode->data = data;
newNode->next = NULL;
if (IsEmpty(list)) {
   //如果没有节点 就把头指针,尾指针的地址都指向newNode
   list->front = newNode;
   list->rear = newNode;
}
else {
    // 如果不止一个节点就把最后一个节点的next指向新节点
    list->rear->next = newNode;
    // 把rear地址指向刚插入的新节点地址
    list->rear = newNode;
   }
 list->length++;
 return true;
    }
    bool delQue(linkQN *list, typeData *data) {
if (!list)return false;
QNode** prve = NULL, *prve_node = NULL;
QNode* last = NULL;
QNode* tem = NULL;
prve = &(list->front);
last = list->front;
tem = last->next;
while (tem)
{
    if (tem->priority > last->priority) {
	cout << "比较出的最大值:" << tem->data << endl;
	prve = &(last->next);
	prve_node = last;
      }
	last = tem; //上一个
	tem = tem->next; //下一个
  }
*data = (*prve)->data;
tem = (*prve);   // 记录删除的节点
*prve = (*prve)->next;
delete tem;
list->length--;
if (list->length == 0) {
	list->rear = NULL;
}
if ((*prve) == NULL) {
	list->rear = prve_node;
}
return true;
 };
 void prinf(linkQN *list) {
QNode *p = NULL;
if (!list)return;
if (IsEmpty(list)) {
	return;
}
p = list->front;
while (p)
{
	cout << p->data << "\t";
	p = p->next;
}
cout << endl;
}
// 清空队列
bool ClearQueue(linkQN *list) {
if (!list) return false;
if (IsEmpty(list)) {
	return false;
}
while (list->front)
{
	QNode *tem = list->front->next;
	delete list->front;
	list->front = tem;
}
list->front = NULL;
list->rear = NULL;
list->length = 0;
return true;
}
// 获取队列长度
int getLength(linkQN *list) {
if (!list)return false;
return list->length;
 }
 void main() {
linkQN *list = new linkQN;

typeData data = -1;
// 1:初始化队列
initLink(list);
//2:插入节点
for (int i = 0; i < 3; i++) {
	EnterQueue(list, (i + 10), i);
}

//打印队列节点个数
cout << "队列个数:" << getLength(list) << endl;

// 打印
prinf(list);

//3: 把队列第一个节点出队
for (int i = 0; i < 3; i++) {
	delQue(list, &data);
}
cout << "第一个出队的值:" << data << endl;
prinf(list);
// 4:清空队列
ClearQueue(list);
prinf(list);
system("pause");

}

推荐阅读