数据结构之队列的Java实现

时间:2022-05-04 17:39:33

Java代码如下:

package com.ds.list;

/**
* 队列,先进先出的链式数据结构
*/
public class MyQueue<T> {

class Node {
public T data;
public Node next;
}

private Node front; //队头
private Node rear; //队尾

public MyQueue() {
Node node = new Node();
node.next = null;
this.rear = this.front = node;
}

//元素入队
public void enQueue(T t) {
Node node = new Node();
node.data = t;
node.next = this.rear;
this.rear = node;
log("enqueue data: " + t);
}

//元素出队
public T deQueue() {
if(this.front == this.rear) {
return null;
}
Node p = this.rear;
while(p.next != this.front) {
p = p.next;
}
T t = p.data;
this.front = p;
return t;
}

private static void log(String msg) {
System.out.println(msg);
}

public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<>();
for(int i = 0; i < 5; i++) {
queue.enQueue("item " + i);
}
log("dequeue data: " + queue.deQueue());
log("dequeue data: " + queue.deQueue());
log("dequeue data: " + queue.deQueue());
log("dequeue data: " + queue.deQueue());
log("dequeue data: " + queue.deQueue());
log("dequeue data: " + queue.deQueue());
}

}
程序运行的结果如下图所示:

数据结构之队列的Java实现