以下代码是我用java实现数据结构中的队列
package com.husiwang.Queue; /** * Created by SiwangHu on 2015/2/2. */ public class Queue { private Object[] Data; //数据缓冲区 private int Capacity; //容量 private int Head; //队首指针 private int Tail; //队尾指针 private int Length; //队列长度 //无参构造函数 public Queue() { Capacity = 20; Head = 0; Tail = 0; Length = 0; Data = new Object[Capacity]; } //有参构造函数 public Queue(int capacity) { if (capacity > 0) { Capacity = capacity; Head = 0; Tail = 0; Length = 0; Data = new Object[Capacity]; } else { throw new RuntimeException("容量不能为空"); } } //获取容量 public int getCapacity() { return Capacity; } //获取队首指针位置 public int getHead() { return Head; } //获取队尾指针位置 public int getTail() { return Tail; } //获取队列长度 public int getLength() { return Length; } //判断队列是否为空 public boolean IsEmpty() { if (Length == 0) return true; else return false; } //扩充容量 public void IncreaseCapacity() { Object[] temp = new Object[Capacity]; for (int i = Head,j=0; Tail < Head ? i!= Tail : i < Tail; i=(i+1)%Capacity,j++) { temp[j]=Data[i]; } Head=0; Tail=Capacity-1; Capacity = Capacity * 2; Data = new Object[Capacity]; for (int i = 0; i < temp.length; i++) { Data[i] = temp[i]; } } //扩充容量 public void IncreaseCapacity(int multiple) { Object[] temp = new Object[Capacity]; for (int i = Head,j=0; Tail < Head ? i!= Tail : i < Tail; i=(i+1)%Capacity,j++) { temp[j]=Data[i]; } Head=0; Tail=Capacity-1; Capacity = Capacity * multiple; Data = new Object[Capacity]; for (int i = 0; i < temp.length; i++) { Data[i] = temp[i]; } } //入队 public void enQueue(Object data) { if (Length < Capacity-1) { Data[Tail] = data; Tail = (Tail + 1) % Capacity; Length++; } else { IncreaseCapacity(); Data[Tail] = data; Tail = (Tail + 1) % Capacity; Length++; } } //出队 public Object deQueue() { if (!IsEmpty()) { Object temp = Data[Head]; Head = (Head + 1) % Capacity; Length--; return temp; } else { throw new RuntimeException("队列为空"); } } //获取队首元素 public Object Peek() { if (!IsEmpty()) { return Data[Head]; } else { throw new RuntimeException("队列为空"); } } @Override public String toString() { String temp = ""; for (int i = Head; Tail < Head ? i!= Tail : i < Tail; i=(i+1)%Capacity) { temp += Data[i] + " "; } return "Queue{" + "Data=" + temp + ", Capacity=" + Capacity + ", Head=" + Head + ", Tail=" + Tail + ", Length=" + Length + '}'; } }