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

队列:C语言实现
	#include <stdio.h>
#include <stdlib.h>
#define QueueIsEmpty(arg) (arg->Size <= 0)
#define QueueIsFull(arg) (arg->Size == arg->Capacity)
/*判断是否为空或为满。宏定义,函数调销太大。
队列使用Size和Capacity显式的判断是否空或满。*/
typedef struct queue_tag
{
    int Size     ;			//记录队列中有多少个元素
    int Rear     ;		//队列尾
    int Front    ;			//队列头
    int Capacity ;			//队列的长度
    int *Array   ;		//元素数组
}*Queue ;

Queue CreatQueue(int NumVertex)
{
    Queue Q ;
    //alloc memory and detect error分配内存并检测错误
     Q = calloc(1, sizeof(struct queue_tag)) ;
    if(!Q){ fprintf(stderr, "Out of space!\n"); exit(1) ; }
    Q->Array = calloc(NumVertex, sizeof(int)) ;
    if(!Q->Array){ fprintf(stderr,"Out of space!\n"); exit(1) ; }
    //初始化队列
     Q->Size = 0 ;
    Q->Rear = 0 ;
    Q->Front= 1 ;
    Q->Capacity = NumVertex ;
    return Q ;
}
int Dequeue(Queue Q)
{
    int Result ;
    if(!QueueIsEmpty(Q))
    {
        Result = Q->Array[Q->Front++] ;
		//回绕队列,当Front到达数组尾时,让Front回绕到数组0(头)处
        if(Q->Front == Q->Capacity)
            Q->Front = 0 ;
        Q->Size -- ;
        return Result ;
    }
    else fprintf(stderr, "Queue is Empty!\n") ;
}
void Enqueue(int e, Queue Q)
{
    if(!QueueIsFull(Q))
    {
        Q->Rear ++ ;
		//回绕
        if(Q->Rear == Q->Capacity)
            Q->Rear = 0 ;
        Q->Size ++ ;
        Q->Array[Q->Rear] = e ;
    }
    else fprintf(stderr, "Out of space!\n") ;
}
void QueueDestory(Queue Q)
{
    if(Q)
    {
        if(Q->Array)
            free(Q->Array) ;
        free(Q) ;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值