c++ 队列算法

include

     using namespace std;
     #define Maxsize 5
     typedef int DataType;

     typedef struct Queue {
    DataType data[Maxsize];
    int front; //循环 队列头指针 
   int rear;   //循环 队列尾指针
      }QueueList;

     void intit(QueueList *list) {
    list->front=list->rear = 0;
     }
     // 队列是否已满
     bool IsFull(QueueList *list) {
    if (!list) return false;
      if ((list->rear + 1) % Maxsize == list->front) {
    return false;
   }
  return true;
  }
  // 队列是否为空
  bool isEmpty(QueueList *list) {
  if (list->rear == list->front) {
    return true;
  }
    return false;
   }
   void showData(QueueList *list) {
    int i = list->front;
    while (i != list->rear)
       {
    cout << list->data[i] << "\t";
    i = (i + 1) % Maxsize;
     }
      }
    void EnterQueue(QueueList *list, DataType datas) {
     if (!list) return;
      if (!IsFull(list)) {
    cout << "队列已满:" << datas << "不能插入此队列" << endl;
    return;
       }
    list->data[list->rear] = datas; // 在队尾插入元素值
    list->rear = (list->rear + 1) % Maxsize; // 队尾指针后移一位
     }
     bool DeleteQueue(QueueList *list, DataType *datas) {
     if (!list || isEmpty(list)) {
     cout << "此队列为空" << endl;
     return false;
    }
   *datas = list->data[list->front];
     list->front = (list->front + 1) % Maxsize;
    return true;
      }
     void ClearQueues(QueueList *list) {
   if (!list) return;
    list->front = list->rear = 0;
     }
     // 获取队列元素 个数
      int getLengths(QueueList *list) {
        return (list->rear - list->front + Maxsize) % Maxsize;
     }
   int main() {
  QueueList *list = new QueueList;
  intit(list);
   for (int i = 0; i < 7; i++)
       {
    EnterQueue(list, i);
      }
   cout << "---------------------入队的值-----------------:" << endl;
   showData(list);
   cout << "队列元素个数:" << getLengths(list) << endl;
   int k = 0;
    int *p = &k;
    cout << "------------------------删除队列元素-----------------------" << endl;
    for (int i = 0; i < 3;i++) {
    DeleteQueue(list, p);
    cout << "出列的值:" << endl;
    cout<< *p <<'\t';
     }
     cout << "队列剩余的值" << endl;
    showData(list);
    cout << "队列元素个数:" << getLengths(list) << endl;
    cout << "--------------删除后再添加元素--------------" << endl;
    for (int i = 0; i < 3;i++) {
      EnterQueue(list, i);
    }
    cout << "入队的值:" << endl;
    showData(list);
    cout << "队列元素个数:" << getLengths(list) << endl;
    system("pause");
   return 0;
    }
上一篇:#树状数组,欧拉函数#CF594D REQ


下一篇:银行家算法Banker‘s Algorithm(c++简单实现)