您的位置:首页 > 理论基础 > 数据结构算法

数据结构之 队列(C语言实现)

2017-03-14 09:51 447 查看

数据结构之 队列(C语言实现)

1. 队列ADT

1.1 介绍

队列(queue)属于表,使用队列时插入在一端进行而删除在另一端进行。

1.2 队列模型

队列的基本操作是Enqueue(入队),它是在表的末端(队尾(rear))插入一个元素,还有Dequeue(出队),它是删除(或返回)在表的开头(队头(front))的元素。如下图:



2. 队列的数组实现

queue.h文件

#ifndef _QUEUE_H_
#define _QUEUE_H_

#define MinQueueSize    5   //最小队列元素

typedef int elementType;

typedef struct queueRecord
{
int capacity;   //队列的最大容量
int front;  //队首元素下标
int rear;   //队尾元素下标
int size;   //队列有多少元素
elementType *array; //指向动态分配的内存
}QUEUE;

int isEmpty(QUEUE *q);      //判空
int isFull(QUEUE *q);       //判满
QUEUE *createQueue(int maxElements);    //创建一个队列
void disposeQueue(QUEUE *q);    //销毁一个队列
void makeEmpty(QUEUE *q);   //构造一个空队列
void enQueue(elementType element, QUEUE *q);    //入队
elementType front(QUEUE *q);        //返回队首元素但不删除
void deQueue(QUEUE *q); //删除队首元素不返回
elementType frontAndDequeue(QUEUE *q);  //出队,返回并删除

#endif


queue.c文件

#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

int isEmpty(QUEUE *q)
{
return (q->size == 0);
}
int isFull(QUEUE *q)
{
return (q->size == q->capacity);
}
QUEUE *createQueue(int maxElements)
{
if(maxElements < MinQueueSize) {
printf("queue size is too small\n");
return NULL;
} else {
QUEUE *q = (QUEUE *)malloc(sizeof(struct queueRecord));
q->array = (elementType *)malloc(sizeof(elementType) * maxElements);
q->capacity = maxElements;
makeEmpty(q);
return q;
}
}
void disposeQueue(QUEUE *q)
{
if(q != NULL) {
free(q->array);
free(q);
}
}
void makeEmpty(QUEUE *q)
{
if(q != NULL) {
q->front = 1;
q->rear = 0;
q->size = 0;
}
}
static int succ(int value, QUEUE *q)
{
if(++value == q->capacity)
value = 0;
return value;
}
void enQueue(elementType element, QUEUE *q)
{
if(!isFull(q)) {
q->size++;
q->rear = succ(q->rear, q);
q->array[q->rear] = element;
} else {
printf("Full queue\n");
}
}
elementType front(QUEUE *q)
{
if(!isEmpty(q)) {
return q->array[q->front];
} else {
printf("empty queue\n");
}
}
void deQueue(QUEUE *q)
{
if(!isEmpty(q)) {
q->size--;
q->front = succ(q->front, q);
} else {
printf("empty queue\n");
}
}
elementType frontAndDequeue(QUEUE *q)
{
if(!isEmpty(q)) {
int ret = q->array[q->front];
q->size--;
q->front = succ(q->front, q);
return ret;
} else {
printf("empty queue\n");
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 数据 adt