首页 > 代码库 > JAVA实现数组队列,循环数组队列,链式队列
JAVA实现数组队列,循环数组队列,链式队列
/** * 文件名:QueueText.java * 时间:2014年10月22日下午9:05:13 * 作者:修维康 */ package chapter3; /** * 类名:ArrayQueue * 说明:队列的数组实现 */ class ArrayQueue<AnyType>{ private static final int DEFAULT_CAPACITY = 10; private int front;//队头 private int rear;//队尾 private int theSize; private AnyType[] theItems; public ArrayQueue(){ clear(); } public void clear(){ front = 0; rear = 0; theSize = 0; ensureCapacity(DEFAULT_CAPACITY); } public boolean isEmpty(){ return theSize == 0;//or front == rear; } public void enqueue(AnyType x){ theItems[rear++] = x; theSize++; } public AnyType dequeue(){ if(theSize == 0) return null; theSize--; return theItems[front++]; } //返回队列前面的元素 public AnyType element(){ if(isEmpty()) return null; return theItems[front]; } /** * 方法名:ensureCapacity * 说明:确保容量 */ public void ensureCapacity(int newCapacity){ if(newCapacity < theSize) return; AnyType[] old = theItems; theItems = (AnyType[]) new Object[newCapacity]; for(int i = 0;i < theSize;i++) theItems[i] = old[i]; } } /** * 类名:CirArrQueue * 说明:循环队列 (因为用数组实现的队列在删除的时候指针会后移 这样导致了前面的浪费, * 循环数组可以解决这个问题,但是循环队列可能使得运行时间加倍) */ class CirArrQueue<AnyType>{ private static final int DEFAULT_CAPACITY = 3; private int front;//队头 private int rear;//队尾 private int theSize; private AnyType[] theItems; public CirArrQueue(){ clear(); } public void clear(){ theItems = (AnyType[]) new Object[DEFAULT_CAPACITY]; front = 0; rear = 0; theSize = 0; } public boolean isEmpty(){ return theSize == 0;//or front == rear; } public boolean enqueue(AnyType x){ if(theSize == DEFAULT_CAPACITY) return false; theItems[rear++] = x; theSize++; if(rear == DEFAULT_CAPACITY)//如果到了尾部则回到0 rear = 0; return true; } public AnyType dequeue(){ if(theSize == 0) return null; theSize--; AnyType temp = theItems[front]; if(++front == DEFAULT_CAPACITY)//如果加1超过了数组 则返回到0; front = 0; return temp; } //返回队列前面的元素 public AnyType element(){ if(isEmpty()) return null; return theItems[front]; } } /** * 类名:LinkedQueue * 说明:链表实现队列 */ class LinkedQueue<AnyType>{ private static class Node<AnyType> { Node(AnyType data, Node<AnyType> next) { this.data = http://www.mamicode.com/data;>JAVA实现数组队列,循环数组队列,链式队列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。