c语⾔顺序循环队列总结,顺序队列及循环队列(C语⾔)⼀、顺序队列
1、头⽂件SqQueue.h
#include
#define MAXSIZE 100
c语言struct头文件typedef struct SqQuene
{
int rear;
void* data[MAXSIZE];
}SqQuene;
void InitQuene(SqQuene*);
int QueneEmpty(SqQuene*);
int QueneLength(SqQuene*);
void GetFront(SqQuene*, void**);
void EnQuene(SqQuene*, void*);
void DeQuene(SqQuene*, void**);
void ClearQuene(SqQuene*);
2、相关操作函数⽂件SqQueue.c
#include
#include
#include "SqQuene.h"
void InitQuene(SqQuene* sq)
{
sq->rear = -1;
memset(sq->data, 0, sizeof(sq->data));
}
int QueneEmpty(SqQuene* sq)
{
if(sq->rear == -1)
return 1;
return 0;
}
int QueneLength(SqQuene* sq)
{
return sq->rear + 1;
}
void ClearQuene(SqQuene* sq)
{
sq->rear = -1;
}
void GetFront(SqQuene* sq, void** e) {
if(sq->rear == -1)
{
printf("队列为空,⽆法出队!\n"); return;
}
*e = sq->data[0];
}
void EnQuene(SqQuene* sq, void* e) {
if(sq->rear == MAXSIZE - 1)
{
printf("队列已满,⽆法⼊队!\n"); return;
}
sq->rear++;
sq->data[sq->rear] = e;
}
void DeQuene(SqQuene* sq, void** e) {
if(sq->rear == -1)
{
printf("空队列,⽆法出队!\n"); return;
}
*e = sq->data[0];
int i = 1;
//该循环⽤于解决假溢出现象,但是开销⽐较⼤,更好的办法是建⽴循环队列for(i = 1; i <= sq->rear; i++)
{
sq->data[i-1] = sq->data[i];
}
sq->rear--;
}
3、主函数测试⽂件main.c
#include
#include
#include "SqQuene.h"
typedef struct stu
{
int id;
int age;
}Student;
int main()
{
SqQuene sq;
InitQuene(&sq);
Student s[10];
int i = 0;
for(i = 0; i < 10; i++)
{
s[i].id = i;
s[i].age = i + 20;
}
for(i = 0; i < 10; i++)
{
EnQuene(&sq, &s[i]);
}
printf("The size of Quene: %d\n", QueneLength(&sq));
while(!QueneEmpty(&sq))
{
Student* tmp;
GetFront(&sq, (void**)&tmp);
printf("当前队头元素值为:%d, %d\n", tmp->id, tmp->age);
//printf("当前队头的元素值为:id = %d, age = %d\n", tmp->id, tmp->age); DeQuene(&sq, (void**)&tmp);
printf("当前出队的元素值为:id = %d, age = %d\n", tmp->id, tmp->age); printf("\n");
}
EnQuene(&sq, &s[0]);
ClearQuene(&sq);
printf("The size of Quene: %d\n", QueneLength(&sq));
return 0;
}
⼆、循环队列
1、头⽂件circle_queue.h
#include
#define MAXSIZE 10
typedef struct cqueue
{
int front;
int rear;
void* data[MAXSIZE];
}cqueue;
void InitQueue(cqueue*);
int QueueEmpty(cqueue*);
int QueueLength(cqueue*);
void GetFront(cqueue*, void**);
void EnQueue(cqueue*, void*);
void DeQueue(cqueue*, void**);
void ClearQueue(cqueue*);
2、相关操作函数circle_queue.c
#include "circle_queue.h"
#include
void InitQueue(cqueue* cq)
{
cq->front = -1;
cq->rear = -1;
memset(cq->data, 0, sizeof(cq->data));
}
int QueueEmpty(cqueue* cq)
{
if(cq->front == cq->rear)
return 1;
return 0;
}
int QueueLength(cqueue* cq)
{
return (cq->rear - cq->front + MAXSIZE) % MAXSIZE; }
void GetFront(cqueue* cq, void** e)
{
if(QueueEmpty(cq))
{
printf("空队列!\n");
return;
}
*e = cq->data[cq->front + 1];
}
void EnQueue(cqueue* cq, void* e)
{
if((cq->rear + 1) % MAXSIZE == cq->front)
{
printf("队满!\n");
return;
}
cq->rear = (cq->rear + 1) % MAXSIZE;
cq->data[cq->rear] = e;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论