一. 基本概念
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
二. 实现
//节点类
public class Node {
public Object data;
public Node next;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Node(Object data) {
this.data = data;
}
}
/**
* 队列:队尾插入,队头删除
*/
public class MyQueue<E> {
//队头
private Node front;
//队尾
private Node rear;
/**
* 入队
* @param element
*/
public void enQueue(E element){
Node node = new Node(element);
if (null == front && null == rear){
front = node;
rear = node;
}else {
rear.next = node;
rear = node;
}
}
/**
* 出队
* @return
*/
public E deQueue(){
if (null == front && null == rear) throw new RuntimeException("队列为空");
Node node = front;
Object obj = node.data;
front = front.next;
if (rear == node)
rear = rear.next;
return (E) obj;
}
/**
* 打印队列元素
* @return
*/
@Override
public String toString() {
if (null == front && null == rear) return "[]";
StringBuilder sb = new StringBuilder("[");
Node temp = front;
sb.append(temp.data+",");
while (temp != rear){
temp = temp.next;
sb.append(temp.data+",");
}
sb.setCharAt(sb.length()-1 , ']');
return sb.toString();
}
}
//测试类
public class TestMyQueue {
public static void main(String[] args) {
MyQueue<String> myQueue = new MyQueue<>();
//System.out.println("出队元素为: "+myQueue.deQueue());
myQueue.enQueue("a");
System.out.println("队列内元素为: "+ myQueue.toString());
System.out.println("出队元素为: "+myQueue.deQueue());
System.out.println("队列内元素为: "+ myQueue.toString());
myQueue.enQueue("a");
myQueue.enQueue("b");
myQueue.enQueue("c");
System.out.println("队列内元素为: "+ myQueue.toString());
System.out.println("出队元素为: "+myQueue.deQueue());
System.out.println("队列内元素为: "+ myQueue.toString());
}
}
测试结果