public interface Queue

  队列类似于现实生活中的排队。队列是先进先出的原则,只允许在队列头部去除元素,队列尾部添加元素。

  下面是分别用数组和链表为存储结构实现的队列

  public interface Queue {

  int size();

  T remove();

  void add(T element);

  boolean isEmpty();

  void clear();

  boolean hasElement();

  }

  public class ArrayQueue implements Queue{

  //数组的默认大小

  private static final int DEFAULT_SIZE = 10;

  //默认用数组存储

  private Object[] values = new Object[DEFAULT_SIZE];

  private int arrayLength = DEFAULT_SIZE;

  //

  private int top = -1;

  private int bottom = -1;

  @Override

  public int size() {

  return (top - bottom) + 1;

  }

  //队列顶端删除元素

  @SuppressWarnings("unchecked")

  @Override

  public T remove() {

  if(isEmpty()){

  throw new NullPointerException();

  }

  T value = (T)values[++top];

  return value;

  }

  //在对列底添加元素

  @Override

  public void add(T element) {

  if(bottom >= arrayLength-1){

  resize();

  }

  values[++bottom] = element;

  }

  @Override

  public boolean isEmpty() {

  return top > bottom;

  }

  @Override

  public void clear() {

  top = bottom = -1;

  }

  @Override

  public boolean hasElement() {

  return top < bottom;

  }

  public void resize(){

  arrayLength = arrayLength + DEFAULT_SIZE;

  Object[] temp = new Object[arrayLength];

  for(int i=0;i<values.length;i++){ temp[i]="values[i];" values="temp;" }="" public="" static="" void="" main(string="" args[]){="" arrayqueue arrayQueue = new ArrayQueue();

  arrayQueue.add(1);

  arrayQueue.add(2);

  arrayQueue.add(3);

  arrayQueue.add(4);

  arrayQueue.add(5);

  arrayQueue.add(6);

  arrayQueue.add(7);

  arrayQueue.add(8);

  arrayQueue.add(9);

  arrayQueue.add(10);

  arrayQueue.add(11);

  while(arrayQueue.hasElement()){

  System.out.println(arrayQueue.remove());

  }

  }

  }

  public class LinkedList implements Queue {

  private int size = 0;

  private Item top ;

  private Item bottom;

  private class Item{

  private T data;

  private Item next;

  Item(T data,Item next){

  this.data = data;

  this.next = next;

  }

  }

  @Override

  public int size() {

  return size;

  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值