网上看了好多实现队列的实现方式,做个个人总结。队列的主要特征就是 先进先出。实现队列基本上有两种思路实现:
1.使用数组(弊端是数据有大小限制,会出现队列已满的情况)
2.通过链表
下面分别来讲一下这两种 方式
1.使用数组的方式
使用数据的方式可以理解为一个队列是一个圆形的数组,分别用两个参数记录队头(front)和队尾(rear)的位置。

如果只是用头和尾来标识的话还不能满足要求,因为刚头和尾相同时,还要区分是空的还是满的情况,所以需要加一个参数记录当前队列个数。
简单的实现代码如下
public class MyQueue<T> {
private Object[] array;
private int size;
private int front;
private int rear;
private int counter;
public MyQueue(int size) {
array = new Object[size];
this.size = size;
this.front = 0;
this.rear = 0;
this.counter = 0;
}
public boolean isFull() {
return this.counter >= this.size;
}
public boolean isEmpty() {
return this.counter <= 0;
}
/**把数据放入队列*/
public boolean push(Object data) {
if(isFull()) return false;
array[this.rear] = data;
this.rear = (this.rear + 1) % this.size;
this.counter ++;
return true;
}
/**删除队列最前面的数*/
public boolean delete() {
if(isEmpty()) return false;
this.front = (this.front+1) % this.size;
this.counter --;
return true;
}
/**出出队并删除数据*/
public T getData(){
if(isEmpty()) return null;
return (T) array[this.front];
}
/**出出队并删除数据*/
public T pull() {
T data = getData();
delete();
return data;
}
}
测试代码
MyQueue1<Integer> queue = new MyQueue1<Integer>(5);
for (int i = 0; i < 20; i++) {
boolean f = queue.push(i);
System.out.println(i + " = " +f);
if(i % 3 == 0) {
System.out.println("输出:"+queue.pull());
}
}
int ind = 0;
while (ind < 30) {
ind ++;
System.out.println(" 输出:"+queue.pull());
}
好了,下面再来介绍通过链表的方式。
2 链表的实现方法
先看下图

链表的方式的思路就是在每个节点存数据的同时记录下一个节点的信息
Node代码
public class Node {
private Object val;
private Node next;
public Node(){}
public Node(Object value) {
val = value;
}
public void setNext(Node next) {
this.next = next;
}
public Object getValue() {
return val;
}
public Node getNext() {
return next;
}
}
队列代码
public class MyQueue {
private Node front = new Node();
private Node rear = front;
public boolean isEmpty() {
return front == rear;
}
/**向队列中放入数据*/
public boolean push(Object o) {
Node node = new Node(o);
this.rear.setNext(node);
this.rear = node;
return true;
}
/**从队列中读取数据*/
public Object pull() {
if(isEmpty()) return null;
Node deNode = front.getNext();
Object val = deNode.getValue();
//判断是否最后一个节点
if(deNode.getNext() == null) {
front = rear;
} else {
front.setNext(deNode.getNext());
}
return val;
}
}
网友评论