【数据结构】自建循环队列(简单数组实现)
程序员文章站
2022-03-08 08:05:07
...
简单的自建的循环队列(很基础),通过简单数组实现。
package MyCollection;
public class MyQueue {
private Object[] objects;
private int front;
private int rear;
private int capacity;
public MyQueue() {
this(10);
}
public MyQueue(int size) {
capacity=size;
front=-1;
rear=-1;
objects=new Object[size];
}
public boolean isEmpty() {
return front==-1;
}
public boolean isFull() {
// TODO Auto-generated method stub
return ((rear+1)%capacity==front);
}
public int getQueueSize() {
return ((capacity-front+rear+1)%capacity);
}
public void enQueue(Object object){
if (isFull()) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
rear=(rear+1)%capacity;
objects[rear]=object;
if (front==-1) {
front=rear;
}
}
}
public Object deQueue() {
Object Data=objects[front];
if (isEmpty()) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Data=objects[front];
if (front==rear) {
front=rear=-1;
}else {
front=(front+1)%capacity;
}
}
return Data;
}
public Object[] getObjects() {
return objects;
}
public void setObjects(Object[] objects) {
this.objects = objects;
}
public int getFront() {
return front;
}
public void setFront(int front) {
this.front = front;
}
public int getRear() {
return rear;
}
public void setRear(int rear) {
this.rear = rear;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
/**
* !!!!!(队列相关测试)
*/
package MyCollection;
public class Test02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyQueue myQueue=new MyQueue(5);
myQueue.enQueue("wangzhe0");
myQueue.enQueue("wangzhe1");
myQueue.enQueue("wangzhe2");
myQueue.enQueue("wangzhe3");
myQueue.enQueue("wangzhe4");
int a=myQueue.getQueueSize();
System.out.println(myQueue.isFull());
}
}
下一篇: vector简单用法