循环队列
当队列不可再继续插入新的队尾元素(数组越界),此事又不宜进行存储再分配扩大数组空间,队列实际空间未占满,巧妙的办法就是将顺序队列臆造为一个环状的空间。
循环队列的存储结构
typedef struct {
QElemType
* base
;
int front
;
int rear
;
}SqQueue
;
基本操作的函数原型说明
Status
InitQueue(SqQueue
& Q
);
int QueueLength(SqQueue Q
);
Status
EnQueue(SqQueue
& Q
, QElemType e
);
Status
DeQueue(SqQueue
& Q
, QElemType
& e
);
void PrintQueue(SqQueue Q
);
基本操作的函数原型说明
Status
InitQueue(SqQueue
& Q
);
int QueueLength(SqQueue Q
);
Status
EnQueue(SqQueue
& Q
, QElemType e
);
Status
DeQueue(SqQueue
& Q
, QElemType
& e
);
void PrintQueue(SqQueue Q
);
Status
InitQueue(SqQueue
& Q
)
{
Q
.base
= (QElemType
*)malloc(MAXQSIZE
* sizeof(QElemType
));
if (!Q
.base
)
exit(OVERFLOW
);
Q
.front
= Q
.rear
= 0;
return OK
;
}
int QueueLength(SqQueue Q
)
{
return (Q
.rear
- Q
.front
+ MAXQSIZE
) % MAXQSIZE
;
}
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
;
}
void PrintQueue(SqQueue Q
)
{
printf("队列为:");
int n
= Q
.front
;
for (int i
= 0; i
< QueueLength(Q
); i
++)
{
printf("%d ", Q
.base
[n
++ % MAXQSIZE
]);
}
printf("\n");
}
完整代码
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXQSIZE 3
typedef int Status
;
typedef int QElemType
;
typedef struct {
QElemType
* base
;
int front
;
int rear
;
}SqQueue
;
Status
InitQueue(SqQueue
& Q
);
int QueueLength(SqQueue Q
);
Status
EnQueue(SqQueue
& Q
, QElemType e
);
Status
DeQueue(SqQueue
& Q
, QElemType
& e
);
void PrintQueue(SqQueue Q
);
Status
InitQueue(SqQueue
& Q
)
{
Q
.base
= (QElemType
*)malloc(MAXQSIZE
* sizeof(QElemType
));
if (!Q
.base
)
exit(OVERFLOW
);
Q
.front
= Q
.rear
= 0;
return OK
;
}
int QueueLength(SqQueue Q
)
{
return (Q
.rear
- Q
.front
+ MAXQSIZE
) % MAXQSIZE
;
}
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
;
}
void PrintQueue(SqQueue Q
)
{
printf("队列为:");
int n
= Q
.front
;
for (int i
= 0; i
< QueueLength(Q
); i
++)
{
printf("%d ", Q
.base
[n
++ % MAXQSIZE
]);
}
printf("\n");
}
int main()
{
SqQueue Q
;
InitQueue(Q
);
EnQueue(Q
, 1);
EnQueue(Q
, 2);
int n
;
DeQueue(Q
, n
);
EnQueue(Q
, 5);
printf("Q.front=%d Q.rear=%d\n", Q
.front
,Q
.rear
);
PrintQueue(Q
);
return 0;
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-50767.html