2.4队列的顺序结构

参考《大话数据结构》:

环境: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.运行结果




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值