首页 > 技术文章 > 任务队列(链表)

linyuxuan 2020-04-10 16:31 原文

include

#include <iomanip>
using namespace std;

#define maxSize 5
 typedef struct _nodeLink {
 int id;
 void(*fun)();
 struct _nodeLink *next;
 }nodeLink;
 typedef struct _Queue{
 int length;
 nodeLink* front;
 nodeLink* rear;
 }Queue;
 typedef nodeLink *QueuePtr;

// 初始化队列
bool initList(Queue* list) {
 if (!list)return false;
 list->front = NULL;
 list->rear=NULL;
 list->length = 0;
 return true;
 }

 //初始化节点(任务队列)
  QueuePtr thread_task_alloc() {
  nodeLink *task;
   task = new nodeLink;
   if (task == NULL) {
    return NULL;
   }
   return task;
  }
 //判断队列为空 
 bool IsEmpty(Queue* list) {
 if (!list) return false;
 if (list->rear == NULL) {
      cout << "队列为空" << endl;
      return true;
 }
 return false;
  }
 //判断队列是否为满 
 bool IsFull(Queue* list) {
if (!list) return false;
if (list->length == maxSize) {
      cout << "队列已满" << endl;
  return true;
}
return false;
}
// 获取队列长度
int getLength(Queue * list) {
if (!list)return false;
 return list->length;
}
// 插入节点
bool EnterQueue(Queue * list, nodeLink* node) {
if (!list)return false;
if (!node)return false;
node->next = NULL;
if (IsEmpty(list)) {
   list->front = node;
   list->rear = node;
}
else {
  list->rear->next = node;
  list->rear = node;
}
list->length++;
return true;
  }
 // 打印
 void prinf(Queue * list) {
if (!list) return;
if (IsEmpty(list)) return;
nodeLink * p = NULL;
p = list->front;
while (p)
{
  cout<<p->id<<endl;
   p = p->next;
 }
   }
  //出队节点
  nodeLink* PopQueue(Queue * list) {
 if (!list)return false;
  nodeLink* tem = NULL;
  if (IsEmpty(list)) {
    return false;
   }
  tem = list->front;
  list->front = tem->next;
  if (!list->front) {
   list->rear = NULL;
  }
  list->length--;
   return tem;
    }
   void test1() {
  cout << "吃饭" << endl;
   }
   void test2() {
   cout << "玩游戏" << endl;
   }
  void mainhj() {
Queue* list = new Queue;
nodeLink* task = NULL;

//1:初始化队列
initList(list);

//2:初始化节点
task = thread_task_alloc();
task->id = 1;
task->fun = &test1;
//3: 插入1
EnterQueue(list, task);

task = thread_task_alloc();
task->id = 2;
task->fun = &test2;
//3: 插入2
EnterQueue(list,task);

  //4: 获取队列长度
cout << "队列个数" << getLength(list) << endl;

//5:打印
 prinf(list);

//6:出队
while (task=PopQueue(list))
 {
    task->fun();
   //删除当前节点
       delete task;
 }
// 销毁队列
delete list;
 system("pause");
   }

推荐阅读