C++学习(三十三)(C语言部分)之 队列

队列测试代码笔记如下:

 1 #include<stdio.h>
 2 #define  SIZE  10
 3  typedef struct Queue
 4 {
 5     int data[SIZE];  //队列的容量
 6     int front;  //头部标志
 7     int tail; //尾部标志
 8 }QUEUE,*PQUEUE;
 9 
10 //1.初始化队列
11  void  Init_Queue(PQUEUE Q)
12  {
13      Q->front = 0;
14      Q->tail = 0;
15      for (int i = 0; i < SIZE; i++)
16      {
17          Q->data[i] = 0;
18      }
19 
20  }
21 
22  //2. 入队
23  void Queue_Push(PQUEUE Q, int data)//参数1:指明要入的队列是哪一个  参数2:要入队的值
24  {
25      // 2.1  判断是不是满的
26      if (((Q->tail+1)%SIZE) == Q->front)
27      {
28          printf("队列满了!无法入队!\n");
29          return;  //满了直接退出!
30      }
31      Q->data[Q->tail] = data;
32      Q->tail++;
33      if (Q->tail == SIZE)  //如果到最后一个+1之后等于第一元素
34      {
35          Q->tail %= SIZE;
36      }
37  }
38 
39  //3. 获取队头的元素
40  int GetQueue(PQUEUE Q)
41  {
42      return Q->data[Q->front];  //返回头部元素
43  }
44 
45  //4. 出队
46  void Pop_Queue(PQUEUE Q)
47  {
48      Q->front++;
49      if (Q->front == SIZE)  //如果到最后一个+1之后等于第一元素
50      {
51          Q->front %= SIZE;
52      }
53  }
54 
55  //5. 判断队列是不是空的
56  int isEmpty(PQUEUE Q)
57  {
58      return Q->front == Q->tail;  //头尾相同说明是空的
59  }
60 
61 
62 int main()
63 {
64     QUEUE MyQueue;
65     Init_Queue(&MyQueue);
66     for (int i = 0; i < 15; i++)
67     {
68         Queue_Push(&MyQueue, i + 1);
69     }
70     //出队
71     while (!isEmpty(&MyQueue))
72     {
73         printf("%d -> ", GetQueue(&MyQueue));
74 
75         Pop_Queue(&MyQueue);
76 
77     }
78     return 0;
79 }

2019-03-31  21:07:51

猜你喜欢

转载自www.cnblogs.com/Yuuki-/p/10633179.html