算法导论-对列queue-java实现

本文介绍了一个简单的队列数据结构的Java实现。该队列使用循环数组存储元素,并提供了enqueue和dequeue方法来添加和移除元素。文章还展示了如何检查队列是否为空或已满,并提供了一个显示队列当前状态的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package datastructure;

public class Queue {
 public static void main(String args[]) {
  Queue q=new Queue(4);
  q.enQueue(1);
  q.enQueue(2);
  q.enQueue(3);
  q.deQueue();
  q.enQueue(4);
  q.display();
 }

 private int maxSize;
 private int[] data;
 private int head, tail;

 public Queue(int maxSize) {
  this.maxSize = maxSize;
  data = new int[maxSize];
  head = 0;
  tail = 0;
 }

 public boolean enQueue(int x) {
  if (!full()) {
   data[tail] = x;
   tail=(tail+1)%maxSize;
   return true;
  } else
   return false;
 }

 public int deQueue() {
  if(!empty()){
   head=(head+1)%maxSize;
   return data[head-1];
  }
  else
   return -255;
 }

 public boolean empty() {
  if (head == tail)
   return true;
  else
   return false;
 }

 public boolean full() {
  if (head == (tail + 1) % maxSize)
   return true;
  else
   return false;
 }

 public void display() {
  int i=head;
  while(i!=tail){
   System.out.print(data[i]+"  ");
   i=(i+1)%maxSize;
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值