Advertisement
gha890826

Circle Queue

Nov 8th, 2019
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // ConsoleApplication9.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. using namespace std;
  7. #define MAX 5
  8.  
  9. class queue{
  10. public:
  11.     void enqueue(int);
  12.     void show(void);
  13.     void dequeue(void);
  14. private:
  15.     int cq[MAX];
  16.     int start=MAX-1;
  17.     int end = MAX - 1;
  18.     bool tag=0;
  19. };
  20.  
  21. void queue::show(void)
  22. {
  23.     cout << "\nQueue list: ";
  24.     if (tag == 0)
  25.     {
  26.         for (int i = (start + 1) % MAX; i != (end + 1) % MAX; i = (i + 1) % MAX)
  27.         {
  28.             cout << cq[i];
  29.         }
  30.     }
  31.     else
  32.     {
  33.         int i = (start + 1) % MAX;
  34.         cout << cq[i];
  35.         i = (i + 1) % MAX;
  36.         for (; i != (end + 1) % MAX; i = (i + 1) % MAX)
  37.         {
  38.             cout << cq[i];
  39.         }
  40.     }
  41.  
  42.     cout << endl;
  43.     for (int i = 0; i < MAX; i++)
  44.     {
  45.         cout << cq[i];
  46.         if (i == start)
  47.             cout << "  <-start";
  48.         if (i == end)
  49.             cout << "  <-end";
  50.         cout << endl;
  51.     }
  52. }
  53. void queue::enqueue(int in)
  54. {
  55.     if (start == end && tag == 1)
  56.         cout << "\nQueue is full when inserting " << in << "!\n";
  57.     else{
  58.         end = ( end+1 ) % MAX;
  59.         cout << "\ninsert "<<in<<"\n";
  60.         cq[end]=in;
  61.         if (start == end)
  62.             tag = 1;
  63.     }
  64. }
  65. void queue::dequeue(void)
  66. {
  67.     if (start == end&&tag == 0)
  68.     {
  69.         cout << "\nQueue is empty!\n";
  70.     }
  71.     else
  72.     {
  73.         start = (start + 1) % MAX;
  74.         cout << "\nDeque " << cq[start] << endl;
  75.         tag = 0;
  76.     }
  77. }
  78.  
  79.  
  80. int main()
  81. {
  82.     queue qu1;
  83.     for (int i = 0; i < 3; i++)
  84.     {
  85.         qu1.enqueue(i+1);
  86.         qu1.show();
  87.     }
  88.     for (int i = 0; i < 2; i++)
  89.     {
  90.         qu1.dequeue();
  91.         qu1.show();
  92.     }
  93.     for(int i = 0; i < 5; i++)
  94.     {
  95.         qu1.enqueue(i + 4);
  96.         qu1.show();
  97.     }
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement