数据结构—循环队列

#include "StdAfx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

//定义循环队列类型
struct Queue
{
	int max;//定义队列最大容量
	int f,r;//定义指向队头队尾的指针
	int *elem;//待会分配队列空间
};
typedef struct Queue *SeqQueue;//为struct Queue*取别名SeqQueue



//创建空循环队列
SeqQueue SetNullQueue(int m)
{
	SeqQueue squeue;
	squeue=(SeqQueue)malloc(sizeof(struct Queue));//为创建的空队列squeue申请结构体空间
	if(squeue!=NULL)//若分配成功则...
	{
		squeue->elem=(int*)malloc(sizeof(int)*m);//为空队列的elem分配空间
		if(squeue->elem!=NULL)
		{
			squeue->max=m;//设置最大空间为m
			squeue->f=0;//设置对头指针初值为0
			squeue->r=0;//设置队尾指针初值为0
			return squeue;
		}
	}
	else
	{
		printf("alloc failure!");
		return NULL;
	}
}



//判断队列是否为空
int IsNullQueue(SeqQueue squeue)
{
	return (squeue->f==squeue->r);//若队头队尾指针值相同则返回1
}



//入队
void InQueue(SeqQueue squeue,int x)//将元素X插入队尾
{
	if((squeue->r+1)%(squeue->max)==squeue->f)//检查是否队满
		printf("full!");
	squeue->elem[squeue->r]=x;//队尾开始放入
	squeue->r=(squeue->r+1)%(squeue->max);//队尾指针加一
}



//出队
void OutQueue(SeqQueue squeue)
{
	if(IsNullQueue(squeue))//判空
		printf("empty!");
	else
		squeue->f=(squeue->f+1)%(squeue->max);//使头指针+1
}



//取队头元素
int FrontQueue(SeqQueue squeue)
{
	if(IsNullQueue(squeue))
		printf("empty!");
	else
		return(squeue->elem[squeue->f]);//返回头指针所指元素
}



//打印顺序队列
void printQueue(SeqQueue squeue)
{
    printf("\n");
    if (IsNullQueue(squeue))
        printf("\n The list is NULL ! \n");
    else
    {
        for (int i = 0;i < squeue->max;i++)
            printf("%d ",squeue->elem[i]);
    }
    printf("\n");
}



//主函数
int main()
{
	int m = 10;//队列的长度m为10
    SeqQueue queue1=SetNullQueue(m);//建空队列
	InQueue(queue1,1);//1入队
	printQueue(queue1);//打印
	OutQueue(queue1);//队首出队
	printQueue(queue1);//打印
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值