参考《大话数据结构》:
环境:ubuntu16.04 vim
文件名称:squeue.h squeue.c main.c Makefile(放到同一个目录下)
实现功能:队列的初始化,队列长度计算,入队及出队操作
1.squeue.h头文件
#ifndef __SQUEUE_HEAD__
#define __SQUEUE_HEAD__
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
#define OK 0
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType data[MAXSIZE];
int front; //头指针
int rear; //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;
/*extern 是变量或函数的申明,告诉编译器在其它文件中找这个变量或函数的定义*/
/*
*初始化一个空队列q
*q [IN, OUT]执行操作的队列
*/
extern Status InitQueue(SqQueue *q);
/*
*返回q的元素个数,也就是队列的当前长度
*q [IN]执行操作的队列
*/
extern int QueueLength(SqQueue q);
/*
*若队列未满,则插入元素e为q新的队尾元素
*q [IN, OUT]执行操作的队列
*e [IN]插入队尾的元素
*/
extern Status EnQueue(SqQueue *q, ElemType e);
/*
*若队列不空,则删除q中队头元素,则e返回其值
*q [IN, OUT]执行操作的队列
*e [IN,OUT]要返回删除的队头元素
*/
extern Status DeQueue(SqQueue *q, ElemType *e);
#endif
2.squeue.c文件
#include "squeue.h"
/*初始化一个空队列q*/
Status InitQueue(SqQueue *q)
{
q->front = 0;
q->rear = 0;
return OK;
}
/*返回q的元素个数,也就是队列的当前长度*/
int QueueLength(SqQueue q)
{
return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
/*若队列未满,则插入元素e为Q新的队尾元素*/
Status EnQueue(SqQueue *q, ElemType e)
{
if (q->front == 0 && q->rear == 0)
{
q->data[q->rear] = e; //将元素e赋值给队尾
q->rear = (q->rear + 1) % MAXSIZE; //rear指针向后移一位置,若到最后则转到数组头部
return OK;
}
if (((q->rear + MAXSIZE) % MAXSIZE) == q->front) //队列满的判断
{
printf("队列已满!\n");
return ERROR;
}
q->data[q->rear] = e; //将元素e赋值给队尾
q->rear = (q->rear + 1) % MAXSIZE; //rear指针向后移一位置,若到最后则转到数组头部
return OK;
}
/*若队列不空,则删除q中队头元素,则e返回其值*/
Status DeQueue(SqQueue *q, ElemType *e)
{
if (q->front == q->rear) //队列空的判断
{
return ERROR;
}
*e = q->data[q->front]; //将队头元素赋值给e
q->front = (q->front + 1) % MAXSIZE; //front指针向后移一位置,若到最后则转到数组头部
return OK;
}
3.main.c文件
#include "squeue.h"
int main()
{
SqQueue q;
//初始化一个空的队列
InitQueue(&q);
//入队列操作
if (EnQueue(&q, 3))
{
printf("enqueue failed!\n");
return ERROR;
}
printf("the length of queue:%d\n", QueueLength(q));
//出队操作
ElemType e = 0;
if (DeQueue(&q, &e))
{
printf("dequeue failed!\n");
return ERROR;
}
printf("e:%d\n", e);
printf("the length of queue:%d\n", QueueLength(q));
return OK;
}
4.Makefile文件
#Makefile for building programmings
OBJS=squeue.o main.o
CC=gcc
CFLAGS=-Wall -g
TARGET=squeue
TARGET:$(OBJS)
$(CC) $(OBJS) -o $(TARGET)
squeue.o:squeue.c squeue.h
$(CC) $(CFLAGS) -c $< -o $@
main.o:main.c squeue.h
$(CC) $(CFLAGS) -c $< -o $@
.PHONY:clean
clean:
rm *.o squeue
5.运行结果