数据结构算法C语言实现(十二)--- 3.4循环队列&队列的顺序表示和实现
一.简述
空队列的处理方法:1.另设一个标志位以区别队列是空还是满;2.少用一个元素空间,约定以队列头指针在队尾指针下一位置上作为队列呈满的状态的标志。
二.头文件
1 //3_4_part1.h
2 /**
3 author:zhaoyu
4 email:zhaoyu1995.com@gmail.com
5 date:2016-6-9
6 note:realize my textbook <<数据结构(C语言版)>>
7 */
8 //Page 64
9 #include <cstdio>
10 #include "head.h"
11 #define QElemType int
12 //----循环队列:队列的顺序存储结构----
13 #define MAXQSIZE 10 //最大队列长度
14 typedef struct{
15 QElemType *base;
16 int front;
17 int rear;
18 }SqQueue;
19 //----循环队列的基本操作说明及实现----
20 Status InitQueue(SqQueue &Q)
21 {
22 //构造一个空队列 Q
23 Q.base = (QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
24 if (!Q.base)
25 {
26 exit(OVERFLOW);
27 }
28 Q.front = Q.rear = 0;
29 return OK;
30 }
31 int QueueLength(SqQueue Q)
32 {
33 //返回 Q 的元素个数,即队列的长度
34 return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
35 }
36 Status EnQueue(SqQueue &Q, QElemType e)
37 {
38 //插入元素 e 为 Q 的新的队尾元素
39 if ((Q.rear+1)%MAXQSIZE == Q.front)
40 {
41 return ERROR;//队列满
42 }
43 Q.base[Q.rear] = e;
44 Q.rear = (Q.rear+1)%MAXQSIZE;
45 return OK;
46 }
47 Status DeQueue(SqQueue &Q, QElemType &e)
48 {
49 //若队列不空,则删除 Q 的队列头元素,用 e 返回其值,
50 //并返回 OK,否则返回 ERROR
51 if (Q.front == Q.rear)
52 {
53 return ERROR;
54 }
55 e = Q.base[Q.front];
56 Q.front = (Q.front+1)%MAXQSIZE;
57 return OK;
58 }
59 void PrintQueue(SqQueue Q)
60 {
61 int cnt = Q.front;
62 if (Q.front == Q.rear)
63 {
64 printf("void\n");
65 return;
66 }
67 while ((cnt+1)%MAXQSIZE != Q.rear)
68 {
69 //printf("%d\t%d\n",Q.base[cnt++], cnt);输出好奇怪
70 printf("%d\t", Q.base[cnt]);
71 cnt++;
72 }
73 printf("%d\n", Q.base[cnt]);
74 }
3_4_part2.h
三.CPP文件
1 #include "3_4_part2.h"
2 int main(int argc, char const *argv[])
3 {
4 SqQueue Q;
5 InitQueue(Q);
6 for (int i = 1; i < 10; ++i)
7 {
8 EnQueue(Q, i*10);
9 }
10 PrintQueue(Q);
11 int e;
12 EnQueue(Q, 100);
13 PrintQueue(Q);
14 DeQueue(Q, e);
15 printf("%d\n", e);
16 EnQueue(Q, 100);
17 PrintQueue(Q);
18 return 0;
19 }
3_4_part2.cpp
四.测试

五.其他
在调试时发现了一点奇怪的错误,后来发现是不同编译器,对自增运算(++/–)在printf语句中作为参数何时执行的解释不同。
下面代码在VS中编译执行和用gcc编译执行的结果是不同的。
1 #include <stdio.h>
2 int main(int argc, char const *argv[])
3 {
4 int cnt = 0, cnt_1 = 0, cnt_2 = 0, cnt_3 = 0, cnt_4 = 0;
5 int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
6 for (int i = 1; i <= 4; i++)
7 {
8 printf("%d-", cnt);
9 printf("%d\t", a[cnt++]);
10 }
11 printf("\n");
12 for (int i = 1; i <= 4; i++)
13 {
14 printf("%d-%d\t", a[cnt_1++], cnt_1);
15 }
16 printf("\n");
17 for (int i = 1; i <= 4; i++)
18 {
19 printf("%d-%d\t", a[++cnt_2], cnt_2);
20 }
21 printf("\n");
22 for (int i = 1; i <= 4; i++)
23 {
24 printf("%d-%d\t", cnt_3, a[cnt_3++]);
25 }
26 printf("\n");
27 for (int i = 1; i <= 4; i++)
28 {
29 printf("%d-%d\t", cnt_4, a[++cnt_4]);
30 }
31 printf("\n");
32 int cnt_5 = 1, cnt_6 = 1, cnt_7 = 1;
33 printf("%d-%d\n", cnt_5, 5*(cnt_5++));
34 return 0;
35 }
tese.c
VS2015编译执行结果

gcc编译执行结果
