数据结构与算法之循环队列的实现

直接上代码
实现语言为C语言

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


#define TRUE    1
#define FALSE   0
#define OK      1
#define ERROR   0
#define INFEASIBLE -1
#define OVERFLOW   -2
#define MAXSIZE    100

typedef int QElemType;
typedef int Status;

typedef struct{
    QElemType *base;//初始化的动态分配内存空间
    int Front;//头指针
    int Rear;//尾指针

}SqQueue;

// 构造空队列
Status InitQueue(SqQueue &Q){
 
    Q.base = new QElemType[MAXSIZE];    // 分配数组空间
    if (!Q.base) 
    return ERROR;
    Q.Front = 0;                        // 头指针 尾指针为0, 队列为空
    Q.Rear = 0;
    return OK;
}
 
// 销毁队列
Status DestroyQueue(SqQueue &Q){
    if (!Q.base) return ERROR;
    delete Q.base;
    Q.base = NULL;
   
    return OK;
}
 
// 清空队列
Status ClearQueue(SqQueue &Q){
    if (Q.Front == Q.Rear) return ERROR;    // 已经是空表
    Q.Rear = Q.Front;
   
    return OK;
}
 
// 求队列长度
int QueueLength(SqQueue Q){
 
    return ((Q.Rear-Q.Front+MAXSIZE)%MAXSIZE);
}
 
// 用e返回Q的队头元素
Status GetHead(SqQueue Q, QElemType &e){
    if (Q.Front == Q.Rear)
        return ERROR;           // 队不能为空
    e = Q.base[Q.Front];        // 返回队头指针元素, 队头指针不变
    return OK;
}
 
// 插入元素e为Q的队尾元素(入队)
Status EnQueue(SqQueue &Q, QElemType e){
 
    if ((Q.Rear+1)%MAXSIZE == Q.Front) return ERROR;    // 队满
    Q.base[Q.Rear] = e;         // 新元素加入队尾
    Q.Rear = (Q.Rear+1)%MAXSIZE;    // 队尾指针+1
    return OK;
}
 
// 删除Q的队头元素,用e返回(出队)
Status DeQueue(SqQueue &Q, QElemType &e){
 
    if (Q.Rear == Q.Front) return ERROR; // 队空
    e = Q.base[Q.Front];                // 保存队头元素
    Q.Front = (Q.Front+1)%MAXSIZE;  // 队头指针+1
    return OK;
}
 
// 遍历队列
Status TraverseQueue(SqQueue Q){
 
    if (Q.Front == Q.Rear) return ERROR;
  
    int temp = Q.Front;
    while (temp < Q.Rear){
     
        printf("%d ",Q.base[temp]);
        temp++;
    }
    
    return OK;
}


int main()
{
    SqQueue Q;
    QElemType e=0;
   

    if(InitQueue(Q))
     printf("Initstack success\n");
   
    //执行入栈操作
    e=11;
    EnQueue(Q,e);
    e=22;
    EnQueue(Q,e);
    e=33;
    EnQueue(Q,e);

 
     printf("the length of the queue is %d\n",(QueueLength(Q)));
  
    if(GetHead(Q,e))
    {
         printf("the Gethead element is %d\n",e);
    }
       

    if(DeQueue(Q,e))
    {
      printf("the delete of the element is %d\n",e);

  
    }
   
    TraverseQueue(Q);
   


   
   if(ClearQueue(Q))  
   {
        printf("clear success!\n");
   
   }

 

   if(DestroyQueue(Q))
   {
        printf("destoryQueue success!\n");
  
   }
   return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值