队列:先进先出,后进后出,FIFO(First In First Out)
1、数组实现——循环队列
1、元素的插入
2、获得队头元素
3、删除队头元素
/**
* @ClassName LoopQueue
* @Description 循环队列
* @Author lzq
* @Date 2018/5/4 20:36
* @Version 1.0
**/
public class LoopQueue {
private int front; //队头
private int rear; //队尾
private int[] elem;
private int usedSize;
private int allSize;
public LoopQueue() {
this(10);
}
public LoopQueue(int size) {
this.elem = new int[size];
this.allSize = size;
this.front = 0;
this.rear = 0;
this.usedSize = 0;
}
/**
* 判满
* @return
*/
public boolean isFull() {
return (this.rear+1)%this.allSize == this.front;
}
/**
* 判空
* @return
*/
public boolean isEmpty() {
return this.front == this.rear;
}
/**
* 入队
* @param val
*/
public void push(int val) {
if(isFull()) {
return;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1)%allSize;
this.usedSize++;
}
/**
* 出队
*/
public void pop() {
if(isEmpty()){
return;
}
this.elem[front] = -1; //如果队列里放的是对象,这应置为空
this.front = (this.front+1)%allSize;
this.usedSize--;
}
/**
* 获得队头元素
* @return
*/
public int getTop() {
if(isEmpty()) {
return Integer.MIN_VALUE;
}
return this.elem[this.front];
}
/**
* 打印
*/
public void show() {
if(isEmpty()) {
return;
}
for(int i = this.front;i != this.rear;i = (i+1)%allSize) {
System.out.print(this.elem[i]+"\t");
}
System.out.println("\n");
}
}
2、链表实现——链式队列
/**
* @ClassName LinkQueue
* @Description 链式队列
* @Author lzq
* @Date 2018/12/4 21:14
* @Version 1.0
**/
public class LinkQueue {
class Entry {
int data;
Entry next;
public Entry() {
this.data = 0;
this.next = null;
}
public Entry(int data) {
this.data = data;
this.next = null;
}
}
private Entry front;
private Entry rear;
private int useSize;
public LinkQueue() {
this.front = null;
this.rear = null;
this.useSize = 0;
}
/**
* 判空
* @return
*/
public boolean isEmpty() {
return this.useSize == 0;
}
/**
* 入队
* @param val
*/
public void push(int val) {
Entry entry = new Entry(val);
if(isEmpty()) {
this.rear = entry;
this.front = this.rear;
}else {
this.rear.next = entry;
this.rear = this.rear.next;
}
this.useSize++;
}
/**
* 出队
*/
public void pop() {
if(isEmpty()) {
return;
}
Entry delete = this.front;
delete = null;
this.front = this.front.next;
this.useSize--;
}
/**
* 得到队头元素
* @return
*/
public int getTop() {
if(isEmpty()) {
return Integer.MIN_VALUE;
}
return this.front.data;
}
/**
* 打印
*/
public void show() {
Entry cur = this.front;
while(cur != null) {
System.out.print(cur.data+"\t");
cur = cur.next;
}
System.out.println();
}
}