教材:严版数据结构

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXQSIZE 100
typedef int Status;
typedef int QElemType;
typedef struct {
QElemType *base;
int front;
int rear;
}SqQueue;

Status InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q.base)
exit(OVERFLOW);
Q.rear = Q.front=0;
return OK;
}

Status CLearQueue(SqQueue &Q)
{
if (!Q.base)
exit(OVERFLOW);
Q.rear = Q.front;
return OK;
}

Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return TRUE;
else
return FALSE;
}

int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front+MAXQSIZE)%MAXQSIZE;
}

Status GetHead(SqQueue Q, QElemType &e)
{
if (Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
return OK;
}

Status EnQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear+1)%MAXQSIZE==Q.front)
return ERROR;
Q.base[Q.rear] = e;
Q.rear=(Q.rear+1)%MAXQSIZE;
return OK;
}

Status DeQueue(SqQueue &Q, QElemType &e)
{
if (Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}

Status QueueTraverse(SqQueue &Q)
{
int p;
if (Q.front == Q.rear)
return ERROR;
p = Q.front;
while (p != Q.rear)
{
printf("%d ", Q.base[p]);
p++;
}
printf("\n");
return OK;
}

void main()
{
int i, n;
QElemType k, h, a, f;
SqQueue Q;
printf("创建一个空队列!\n");
InitQueue(Q);
printf("判断队列是否为空!\n");
printf("QueueEmpty(Q)=%d\n", QueueEmpty(Q));
printf("创建队列的元素个数:\n");
cin >> n;
printf("输入%d个插入队列的元素的值:\n", n);
for (i = 0; i < n; i++)
{
cin >> k;
EnQueue(Q, k);
}
printf("输出队列元素的值:\n");
QueueTraverse(Q);
printf("输入插入队列的元素的值:");
cin >> h;
EnQueue(Q, h);
printf("输出插入一个队列元素后队列元素的值:\n");
QueueTraverse(Q);
DeQueue(Q, a);
printf("输出第1个删除的队头元素的值:%d\n", a);
DeQueue(Q, a);
printf("输出第2个删除的队头元素的值:%d\n", a);
printf("输出两次删除队头元素后队列的元素值:");
QueueTraverse(Q);
if (!GetHead(Q, f))
printf("输出队头元素的值:%d\n", f);
printf("输出队列元素的个数:%d\n", QueueLength(Q));
printf("将Q清为空队列!\n");
CLearQueue(Q);
printf("输出队列元素的个数:%d\n", QueueLength(Q));
printf("判断队列是否为空!\n");
printf("QueueEmpty(Q)=%d\n", QueueEmpty(Q));
system("pause");
}