c语言实现循环队列

  • 接口参考严蔚敏老师的数据结构
  • 难点
    • 开始队列为空时front = rear = 0,队列满时如果也是front = rear,则很难判断空满两个状态,因此队列空出一个空间专门用来放尾指针。
    • 循环队列如何达到循环状态,接口函数实现的过程最好画图来形象的展示,实现后一个个调试,因为一不小心就可能出错误。
  • 实现环境:linux

下面是实现过程

数据结构:

typedef struct {
	Item *base;
	int front;
	int rear;
}Queue;

queue.h

#ifndef QUEUE_H_
#define QUEUE_H_
#include 

#define MAXQSIZE 6
#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef int Item;

typedef struct {
	Item *base;
	int front;
	int rear;
}Queue;

/*initialize the queue*/
void InitQueue(Queue *q);

/*return the length of the queue*/
unsigned int QueueLength(Queue q);

/*Destroy the queue*/
void DestroyQueue(Queue *q);

/*determine if the queue is empty*/
bool IsEmpty(Queue q);

/*determine if the queue is full*/
bool IsFull(Queue q);

/*return the head elem of the queue*/
Item Top(Queue q);

/*return the back elem of the queue*/
Item Back(Queue q);

/*enqueue, insert the rear*/
bool EnQueue(Queue *q, Item e);

/*dequeue, pop the front*/
bool DeQueue(Queue *q);

/*print the queue*/
void PrintQueue(Queue q);

#endif



queue.c

#include "queue.h"
#include 
#include 

void InitQueue(Queue *q) {
	q->base = (Item*)malloc(MAXQSIZE * sizeof(Item));
	if (q->base == NULL)
		exit(OVERFLOW);
	q->front = 0;
	q->rear = 0;
}

/*return the length of the queue*/
unsigned int QueueLength(Queue q) {
	return (q.rear - q.front + MAXQSIZE) % MAXQSIZE;
}
/*Destroy the queue*/
void DestroyQueue(Queue *q) {
	q->base = NULL;
	q->rear = 0;
	q->front = 0;
	free(q->base);
}

/*determine if the queue is empty*/
bool IsEmpty(Queue q) {
	return q.rear == q.front;
}

bool IsFull(Queue q) {
	return (q.rear + 1) % MAXQSIZE == q.front;
}

/*return the head elem of the queue*/
Item Top(Queue q) {
	return q.base[q.front];
}

/*return the back elem of the queue*/
Item Back(Queue q) {
	return q.base[(q.rear - 1 + MAXQSIZE) % MAXQSIZE];
}

/*enqueue, insert the rear*/
bool EnQueue(Queue *q, Item e) {
	if (IsFull(*q))
		return ERROR;
	q->base[q->rear] = e;
	q->rear = (q->rear + 1) % MAXQSIZE;
	
	return OK;
}
/*dequeue, pop the front*/
bool DeQueue(Queue *q) {
	if(IsEmpty(*q))
		return ERROR;
	q->front = (q->front + 1) % MAXQSIZE;
	return OK;
}

/*print the queue*/
void PrintQueue(Queue q) {
	int i, j;
	for (i = 0, j = q.front; i < QueueLength(q); i++, j = (j + 1) % MAXQSIZE) {
		printf("%d\n",q.base[j]);
	}
}

main.c

#include "queue.h"
#include 
int main () {
	Queue q;
	InitQueue(&q);
	EnQueue(&q, 1);
	EnQueue(&q, 2);
	EnQueue(&q, 3);
        EnQueue(&q, 4);
	EnQueue(&q, 5);
	if (IsFull(q))
		printf("hihi\n");
	DeQueue(&q);
	printf("%d\n%d\n", q.front, q.rear);
        EnQueue(&q, 6);
	printf("%d\n", Top(q));
	//printf("%d\n", q.base[0]);
	printf("%d\n", Back(q));
	PrintQueue(q);
	DestroyQueue(&q);	
}

Makefile

object = main.o queue.o

test : $(object)
	gcc -g -Wall -o test $(object)

main.o : queue.h
queue.o : queue.h

.PHONY : clean
clean :
	rm -rf *.o

你可能感兴趣的:(数据结构)