<队列> 基本概念

队列
  先进先出,后进后出,银行排队取钱,羽毛球桶
  初始化数组作为队列:
    ——— ——— —— ——— ——

    ——— ——— —— ——— ——
    ↑_h == ↑_t
  空队列时,头指针和尾指针相等
  两个指针,一个固定一个移动
  入队列:
    每压入第一个元素,尾部指针往后移动一格指向空,头指针不变 notice:
    ——— ——— —— ——— ——
    a1  a2  
    ——— ——— —— ——— ——
    ↑_h      ↑_t
    ——— ——— —— ——— ———
    a1  a2  a3 a4  a5  
    ——— ——— —— ——— ——— 
    ↑_h                  ↑_t
  出队列:
    头指针指向的元素弹出后,头指针指向下一个元素,尾指针不变 notice:
    ——— ——— —— ——— ——
        a2  a3 a4  a5
    ——— ——— —— ——— ——
        ↑_h           ↑_t
  
  假溢出
     0    1  2   3  4
    ——— ——— —— ——— ——
         a1 a2  a3 a4 
    ——— ——— —— ——— ——
         ↑_h          ↑_t
    当前队列并不是真正的没有空间了,而是尾指针已经超过最大下标了
  循环队列避免假溢出
     4      0    1  2   3
    ——— ——— ——— —— ——— ——  
    a5      a1  a2 a3  a4
    ——— ——— ——— —— ——— ——
        ↑_t ↑_h
    要表示队列为满时智能浪费一个空间,若tail+1 == head -->队列为满
    notice: 为了避免出现假溢出,使用循环队列
    max = 5
    (tail+1) % max = 0 = head
#include <iostream>

#define SIZE  512
using namespace std;

char queue[SIZE];
int head = 0, tail = 0;


void enqueue(char c);
char dequeue();
int isempty();
int isfull(void);

int main(void)
{

  char c = 'A';
  int i;
  for (i = 0; i < 3; i++)
  {
    if(!isfull())
    {
      enqueue(c);
      c++;
    }

  }

  while(!isempty())
  {
    cout << dequeue() << endl;
  }
  cout << "队列为空!" << endl;
  

  return 0;
}


// 入队列:尾指针移动
void enqueue(char c)
{
  // 把数据放到尾部位置,尾部指针后移一格
  queue[tail] = c;
  // 考虑到循环队列
  tail = (tail + 1) % SIZE;
  cout << "tail = " << tail << endl;
}

// 出队列:头指针移动
char dequeue()
{
  // 头指针指向的元素弹出后,头指针指向下一个元素
  char ch;
  // 保存当前出队列的数据
  ch = queue[head];

  // notice: 头指针下移
  head = (head + 1) % SIZE;
  cout << "head = " << head << endl;


  return ch;
}

// 判断队列是否为空,头指针==尾指针
int isempty()
{
  return head == tail;
}

// 判断队列是否为满,若为满返回1
int isfull(void)
{
  return (tail+1) % SIZE == head;
}

/*

tail = 1
tail = 2
tail = 3
head = 1
A
head = 2
B
head = 3
C
队列为空!

*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值