您的位置:首页 > 理论基础 > 数据结构算法

数据结构之-java实现-队列

2016-10-19 14:43 441 查看
队列

队列接口:

public interface Queue {

public boolean append(Object obj) throws Exception;//入队

public Object delete() throws Exception; //出队

public Object getHead() throws Exception;//获取队头元素

public int size();  //队列大小

public boolean isEmpty(); //判断队列是否为空

public boolean isFull();//判断队列是否已满

public void clear();//置空队列
}


队列实现:

public class LinkListQueue implements Queue {

private static final int defaultSize = 10;  //默认大小
private int front;                          //队头指针
private int rear;                           //队尾指针
private int count;                          // 元素个数计数器
private int maxQueueSize;                   //最大元素个数
private Object[] queue;                     //对象数组

//带参数的构造函数,创建指定大小的队列空间
public LinkListQueue(int size) {
queue = new Object[size];
maxQueueSize = size;
front = rear = 0;
}

//无参数的构造函数,创建默认大小的队列空间
public LinkListQueue() {
maxQueueSize = defaultSize;
count = 0;
queue = new Object[defaultSize];
}

//入队列
public boolean append(Object obj) throws Exception {
if (!isFull()) {                         //不满则执行的入队列操作
queue[rear] = obj;                   //将新元素放入队列
rear = (rear + 1) % maxQueueSize;    //加1求模,设定对尾指针
count++;                             //元素计数器加1
return true;
} else {
System.out.println("队列已满!" + obj + "无法插入队列");
return false;
}
}

public Object delete() throws Exception {
Object oRet = null;
if (!isEmpty()) {                      //不空则执行出队列操作
oRet = queue[front];               //获取对头元素
front = (front + 1) % maxQueueSize;//加1后求模,设定队头指针的值
count--;                           //元素计数器减1
} else {
System.out.println("队列已空!");
}
return oRet;
}

public Object getHead() throws Exception {
Object oRet = null;
if (!isEmpty()) {                   //队列不空
oRet = queue[front];            //获取对头元素

} else {
System.out.println("队列已空!");
}

return oRet;
}

public int size() {
return count;
}

public boolean isEmpty() {
return count == 0;
}

public boolean isFull() {

return (count > 0) && (rear == front);
}

public void clear() {
count = 0;              //元素计数器清0
front = rear = 0;       //队头指针与对尾指针指向初始位置
}

}


队列测试:

public class Test {

public static void main(String[] args) {
LinkListQueue queue = new LinkListQueue();
int[] a = {1, 2, 3, 4, 5, 6, 7};
try {
for (int i = 0; i < a.length; i++) {
queue.append(new Integer(a[i]));
}
System.out.println("输出队列大小:");
System.out.println(queue.size());
System.out.println("输出队列内容:");
while (!queue.isEmpty()) {
System.out.println(queue.delete().toString());
}

} catch (Exception ex) {
ex.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息