首先定义Queue接口
package com.chen.arithmetic_test.queue_test;
/**
* Created by ChenMP on 2017/7/5.
*/
public interface Queue {
//入队
public void append(Object obj) throws Exception;
//出队
public Object delete() throws Exception;
//获取头元素
public Object getFront() throws Exception;
//队列是否为空
public boolean isEmpty();
}
定义Node节点
package com.chen.arithmetic_test.queue_test;
/**
* Created by ChenMP on 2017/7/5.
*/
public class Node {
private Object nodeData;
private Node nextNode;
public Node() {
super();
}
public Node(Object nodeData) {
this.nodeData = nodeData;
}
public Object getNodeData() {
return nodeData;
}
public void setNodeData(Object nodeData) {
this.nodeData = nodeData;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
定义Queue的实现类
package com.chen.arithmetic_test.queue_test;
/**
* Created by ChenMP on 2017/7/5.
*/
public class LinkQueue implements Queue {
private Node frontNode; //队首节点
private Node rearNode; //队尾节点
private int size; //队列大小
private int maxSize; //队列最长大小
public LinkQueue() {
this.frontNode = null;
this.rearNode = null;
this.size = 0;
this.size = 10; //设置默认大小
}
public LinkQueue(int maxSize) {
this.frontNode = null;
this.rearNode = null;
this.size = 0;
this.maxSize = maxSize;
}
@Override
public void append(Object obj) throws Exception {
if (size == maxSize)
throw new Exception("队列已满!!!");
Node concurrentNode = new Node(obj);
if (0 == size) {// 队列为空时,对首和队尾指向同一个Node对象
this.rearNode = concurrentNode;
this.frontNode = concurrentNode;
this.size++;
} else {
this.rearNode.setNextNode(concurrentNode);
this.rearNode = concurrentNode;
this.size++;
}
}
@Override
public Object delete() throws Exception {
if (0 == size)
throw new Exception("队列为空!!!");
Object obj = this.frontNode.getNodeData();
this.frontNode = frontNode.getNextNode();
this.size--;
return obj;
}
@Override
public Object getFront() throws Exception {
if (0 == size)
throw new Exception("队列为空!!!");
return this.frontNode.getNodeData();
}
@Override
public boolean isEmpty() {
return this.size>0?false:true;
}
}
编写测试类
package com.chen.arithmetic_test.queue_test;
/**
* Created by ChenMP on 2017/7/5.
*/
public class Test {
public static void main(String[] args) throws Exception {
LinkQueue queue = new LinkQueue(12);
for (int i=0; i<12; i++) {
queue.append(i);
}
for (int i=0; i<3; i++) {
System.out.print(queue.delete() + " ,");
}
System.out.println();
queue.append(12);
queue.append(13);
queue.append(14);
while (!queue.isEmpty()) {
System.out.print(queue.delete() + " ,");
}
}
}