使用数组的方式实现方式
/**
* @author 魏文思 静态队列的实现
* @date 2019/8/29$ 17:50$
*/
public class StaticQueue {
private Object data[];
//队列头
private int front;
//队列尾
private int rear;
//队列大小
private int size;
public StaticQueue(int size) {
this.size = size;
data = new Object[size];
}
//入队
public void in(Object value) throws Exception {
if (rear == size) {
throw new RuntimeException("队列已满");
}
data[rear++] = value;
}
//出队
public Object out() throws Exception {
if(isEmpty()){
throw new RuntimeException("空队列异常");
}
Object value=data[front];
data[front++]=null;
return value;
}
/**
* 是否为空队列
* @return
*/
public boolean isEmpty(){
return front == rear;
}
//遍历队列
public void traverse(){
for (int i=front; i<rear; i++){
System.out.println(data[i]);
}
}
public static void main(String[] args) throws Exception {
StaticQueue queue = new StaticQueue(10);
queue.in(1);
queue.in("ssfdf");
queue.in("sdsfsf");
queue.traverse();
Object out = queue.out();
System.out.println("出来的一个数据: "+out);
queue.traverse();
}
}
使用节点的方式实现
/**
* @author 魏文思 动态队列通过链表实现 有个头指针指向队列头
* @date 2019/8/29$ 19:29$
*/
public class DymicQueue<E> {
private class Node {
//链表某个节点的实际值
public E e;
//链表某个节点的下一个节点
public Node next;
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this(e, null);
}
public Node() {
this(null, null);
}
@Override
public String toString(){
return e.toString();
}
}
//链表的头节点和尾结点
private Node head, tail;
private int size;
public DymicQueue() {
}
//返回队列的大小
public int size() {
return size;
}
//返回队列是否为空
public boolean isEmpty() {
return size == 0;
}
//插入队列数据
public void in(E e) {
if (tail == null) { //如果队列尾为空说明队列为空
tail = new Node(e);//将数据给队尾
head = tail;//对首和队尾一样
} else {
tail.next = new Node(e);//新添加的元素放入队列的尾
tail = tail.next;//更新队列的头部指向新的尾
}
size++;
}
//出队 队列出去一个数据
public E out() {
if (this.isEmpty())
throw new RuntimeException("队列为空");
//出去的是队列的头部数据。拿到头部数据
Node res = head;
head = head.next;
res.next = null;
if (head == null)
tail = null;
size--;
return res.e;
}
//获取队列的头
public E getFront() {
if (this.isEmpty())
throw new IllegalArgumentException("队列为空,getFront失败。");
return head.e;
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append("YgzLinkedQueue: head ");
Node cur = head;
while(cur != null) {
res.append(cur + "->");
cur = cur.next;
}
res.append(" tail");
return res.toString();
}
public static void main(String[] args) {
DymicQueue<Object> dymicQueue=new DymicQueue<>();
dymicQueue.in(1);
dymicQueue.in(2);
dymicQueue.in("嘿嘿");
dymicQueue.in("哈哈");
System.out.println(dymicQueue.toString());
System.out.println(dymicQueue.getFront());
}
}
二者的实现方式都很简单,搞清楚队列的模型,再把模型用面向对象的思想设计出来,动态队列的核心就是搞清每个对象的属性。
一个Node的内部类代表了当前节点的元素,和下一个节点的元素外部类通过控制这些节点的位置,实现数据的存储,看着就一个类,但是存储了我们所需要的数据,有点递归的意思。