数组实现队列
import org.apache.poi.ss.formula.functions.T;
public class MyQueue {
private int cnt;
private int queueSize;
private T[] arr;
public MyQueue(int capacity){
this.cnt = 0;
this.queueSize = capacity;
this.arr = (T[]) new Object[capacity];
}
public boolean isEmpty(){
return this.cnt == 0;
}
public T getHead() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
return arr[0];
}
public T deQueue() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
T temp = arr[0];
System.arraycopy(arr,1,arr,0,cnt-1);
this.cnt--;
return temp;
}
public void enQueue(T value) throws Exception {
if (queueSize == cnt){
throw new Exception("ERROR");
}
arr[cnt] = value;
this.cnt++;
}
public int getLength(){
return this.cnt;
}
public void clearQueue(){
for (int i = 0; i < cnt; i++) {
arr[cnt] = null;
}
this.cnt = 0;
}
}
链表实现队列
import org.apache.poi.ss.formula.functions.T;
public class MyQueue1 {
private int cnt;
private Node head;
private Node tail;
private class Node {
private T value;
private Node next;
public Node(T t, Node next) {
this.value = t;
this.next = next;
}
public Node(T t) {
this(t, null);
}
}
public MyQueue1() {
this.cnt = 0;
this.head = null;
}
public boolean isEmpty() {
return this.cnt == 0;
}
public T getHead() throws Exception {
if (isEmpty()) {
throw new Exception("ERROR");
}
return head.value;
}
public T deQueue() throws Exception {
if (isEmpty()) {
throw new Exception("ERROR");
}
T res = head.value;
head = head.next;
this.cnt--;
return res;
}
public void enQueue(T value) throws Exception {
if (isEmpty()){
head = new Node(value);
tail = head;
}else {
Node curr = new Node(value);
tail.next = curr;
tail = curr;
}
this.cnt++;
}
public int getLength() {
return this.cnt;
}
public void clearQueue() {
this.head = null;
this.cnt = 0;
}
}