数据结构学习一 队列:循环队列02

本文详细介绍了一种使用数组实现的循环队列数据结构。通过设定队头和队尾元素坐标,文章阐述了循环队列的入队、出队操作,并讨论了队空和队满的判断条件。同时,引入标志位来区分队列状态,确保队列操作的正确性。
package queue;

public class MyCircularQueue {
	  int[] equeue ;
      int start=0;
      int end = 0;
      boolean status = true;
   /** Initialize your data structure here. Set the size of the queue to be k. */
   public MyCircularQueue(int k) {
        equeue = new int[k];
        start = end = 0;
        status = true;
   }
   
   /** Insert an element into the circular queue. Return true if the operation is successful. */
   public boolean enQueue(int value) {
       if(isFull()){ 
           return false;
       }
       end = (end+1)%equeue.length;
       if(start==end && status) status = false;
       equeue[end]=value; 
      
       return true;
   }
   
   /** Delete an element from the circular queue. Return true if the operation is successful. */
   public boolean deQueue() {
       if(isEmpty())
           return false;
       start=(start+1)%equeue.length;
       if(start == end && !status) status = true;
       
       return true;
   }
   
   /** Get the front item from the queue. */
   public int Front() {
	   if (isEmpty()) return -1;
       return equeue[start];
   }
   
   /** Get the last item from the queue. */
   public int Rear() {
	   if (isEmpty()) return 4;
       return equeue[end];
   }
   
   /** Checks whether the circular queue is empty or not. */
   public boolean isEmpty() {
       if(start==end && status)
           return true;
       return false;
   }
   
   /** Checks whether the circular queue is full or not. */
   public boolean isFull() {
       if(start==end && !status)
           return true;
       return false;
   }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyCircularQueue obj = new MyCircularQueue(3);
		boolean param_1 =obj.enQueue(1);
		boolean param_0 =obj.enQueue(2);
		boolean param_2 =obj.enQueue(3);
		//boolean param_2 = obj.enQueue(4);
		System.out.println(param_0);
		System.out.println(param_1);
		System.out.println(param_2);
		System.out.println(obj.isEmpty());
		System.out.println(obj.isFull());
	}

}

思路

  • 用数组代替队列
  • 设定代表队头元素和队尾元素的坐标
  • 循环队列队空和队满的判断条件一样,则设定一个标志位判断
  • 入队先判满,不满则队尾++并对队列长度取余
  • 出队先判空,不空则队首++并对队列长度取余
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值