数据结构(初始化牺牲空间实现循环队列)

牺牲一个存储空间来实现循环队列的队满判断

#include <iostream>
using namespace std;
#define MaxSize 10
#define ElementType int
#define Status bool
#define OK true

typedef struct
{
  /* data */
  ElementType *base; // 存储空间的基地址
  int front;         // 头指针
  int rear;          // 尾指针
} SqQueue;

Status InitQueue(SqQueue &Q)
{
  Q.base = new ElementType[MaxSize + 1];
  if (!Q.base)
    exit(0);
  Q.front = Q.rear = 0; //队列为空
  return OK;
}

Status isEmpty(SqQueue &Q)
{
  if (Q.rear != Q.front)
    return false;
  return OK;
}

// 获取队列长度
ElementType getLength(SqQueue Q)
{
  return (MaxSize + Q.rear - Q.front) % MaxSize;
}

Status EnQueue(SqQueue &Q, ElementType e)
{
  if ((Q.rear + 1) % MaxSize == Q.front) // 判断队满
    return false;
  Q.base[Q.rear] = e;
  Q.rear = (Q.rear + 1) % MaxSize;
  return OK;
}

Status PopQueue(SqQueue &Q, ElementType &e)
{
  if (Q.rear == Q.front)
    return false;
  e = Q.base[Q.front];
  Q.front = (Q.front + 1) % MaxSize;
  return OK;
}

ElementType getQueueTop(SqQueue &Q)
{
  if (Q.front != Q.rear)
    return Q.base[Q.front];
}
int main()
{
  SqQueue Q;
  InitQueue(Q);
  for (int i = 0; i < 10; i++)
  {
    if (EnQueue(Q, i))
      cout << "入队成功" << i << endl;
    else
      cout << "入队失败" << endl;
  }
  cout << "-------------------------------" << endl;

  cout << "出栈顺序:" << endl;
  while (!isEmpty(Q))
  {
    int x = 0;
    PopQueue(Q, x);
    cout << "栈顶元素:" << getQueueTop(Q) << endl;
    cout << x << endl;
  }
  system("pause");
  return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值