一.创建队列接口
public interface Queue {
void offer(Object data);
Object peek();
void display();
boolean isEmpty();
int size();
void clear();
}
二.数组实现循环队列
public class ArrayQueue implements Queue {
private final Object[] elements;
private int front;
private int rear;
private int initCapacity = 8;
ArrayQueue() {
elements = new Object[initCapacity];
front = 0;
rear = 0;
}
@Override
public void offer(Object data) {
if ((rear + 1) % initCapacity == front) {
System.out.println("Queue is overflow");
} else {
elements[rear] = data;
rear = rear + 1;
}
}
@Override
public Object peek() {
if (isEmpty()) {
System.out.println("Queue is Empty");
throw new RuntimeException("Queue is Empty");
} else {
Object data = elements[front];
front = (front + 1)%initCapacity;
return data;
}
}
@Override
public void display() {
if (front != rear ) {
for (int i = front; i < front+ size(); i++) {
System.out.println(elements[i%initCapacity]);
}
}
}
@Override
public boolean isEmpty() {
return front == rear;
}
@Override
public int size() {
return (rear - front + initCapacity)%initCapacity;
}
@Override
public void clear() {
}
}
三.链表实现队列
public class LinkQueue implements Queue{
private Node frontNode;
private Node rear;
private int size;
LinkQueue(){
frontNode = null;
rear = null;
}
@Override
public void offer(Object data) {
if (size() == 0) {
rear = new Node(data);
frontNode = rear;
size++;
}else {
Node node = new Node(data);
rear.next = node;
rear = node;
size++;
}
}
@Override
public Object peek() {
if (size() == 0) {
throw new RuntimeException("queue is empty");
}else {
frontNode = frontNode.next;
size--;
return frontNode.data;
}
}
@Override
public void display() {
if (frontNode != null) {
System.out.println( frontNode.data.toString());
Node curNode = frontNode;
while (curNode.next != null) {
curNode = curNode.next;
System.out.println( curNode.data.toString());
}
}
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public int size() {
return size;
}
@Override
public void clear() {
}
class Node{
Object data;
Node next;
Node() {
}
public Node(Object data) {
this.data = data;
}
}
}