实现循环队列

利用数组实现循环队列,head == tail并不能判断队列空与满,需要另外加上一个辅助
#include<cstdlib>
#include<iostream>
#include<string>
using namespace std;
typedef struct node
{
     string key;
     string value;
     node *next;
}node;
#define LEN 20
typedef   int Elemtype;
class Queue
{
public:
       int head;
       int tail;
       int flag;
       Elemtype q[LEN];       
       Queue()
       {
              head = tail = 0;
              flag = 0;
              memset(q,-1,sizeof(q));
       }
       int enqueue(Elemtype e)
       {
           if( head == tail &&  flag == 1)
           {
                   cout << "queue full" << endl;
                   return -1;
           }
           q[tail] = e;
           tail = (tail + 1) % LEN;
           if(head == tail)flag = 1;
           return 0;
       }
       int dequeue(Elemtype &e)
       {
           if(head == tail && flag == 0)
           {
                   cout << "queue empty" << endl;
                   return -1;
           }
           e = q[head];
           head = (head + 1) % LEN;
           if(head == tail) flag = 0;
           return 0;
       }
};

int main()
{
    class Queue que;
    int i ;
    Elemtype elem;
    for(i = 0;i < 1000;i ++)
    {
          if(i % 3)
          {
               que.enqueue(i);
          }
          else 
          {
              int ret =  que.dequeue(elem);
              if(ret >= 0)cout << "i = " << i << " dequeue is :" << elem << endl;
          }
          system("pause");
    }

    return 0;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java实现循环队列可以使用数组来实现,具体实现方法如下: 1.定义一个数组和两个指针front和rear,分别指向队列的头和尾。 2.在队列为空时,front和rear都指向-1。 3.在队列中加入元素时,先判断队列是否已满,如果已满则无法加入元素,否则将rear指针向后移动一位,并将元素加入rear指针所指向的位置。 4.在队列中删除元素时,先判断队列是否为空,如果为空则无法删除元素,否则将front指针向后移动一位,并返回front指针所指向的元素。 5.在判断队列是否为空时,如果front和rear指针都指向-1,则队列为空。 6.在判断队列是否已满时,如果rear指针已经指向数组的最后一个位置,且front指针不在数组的第一个位置,则队列已满。 下面是Java实现循环队列的代码示例: ```java public class CircularQueue { private int[] queue; private int front; private int rear; private int size; public CircularQueue(int k) { queue = new int[k]; front = -1; rear = -1; size = k; } public boolean isEmpty() { return front == -1 && rear == -1; } public boolean isFull() { return (rear + 1) % size == front; } public void enQueue(int data) { if (isFull()) { System.out.println("Queue is full!"); return; } if (isEmpty()) { front = 0; rear = 0; } else { rear = (rear + 1) % size; } queue[rear] = data; } public int deQueue() { if (isEmpty()) { System.out.println("Queue is empty!"); return -1; } int data = queue[front]; if (front == rear) { front = -1; rear = -1; } else { front = (front + 1) % size; } return data; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值