使用java实现队列数据结构


Node节点元素:

public class Node<T> {
private T data;
private Node next;

public T getData() {
return this.data;
}

public void setData(T data) {
this.data = data;
}

public Node getNext() {
return this.next;
}

public void setNext(Node next) {
this.next = next;
}

public Node(T data) {
this.data = data;
}
}
队列实现:
  
public class LinkQueue<T> {
private Node<T> front; //队列头部
private Node<T> rear; //队列尾部
private int size; //队列长度

//指定队列的构造方法,并且做节点的初始化
public LinkQueue() {
front = rear = null;
}

//入队
public void putQueue(T t) {
//创建队列的一个节点
Node<T> tNode = new Node<>(t);
if(isEmpty()) {
front = rear = tNode;
}else {
this.rear.setNext(tNode);
this.rear = tNode; //始终指定队尾的元素
}
size ++; //记录插入Node个数
}

//出队
public T popQueue() throws Exception {
//判断队列是否为空
if(isEmpty()) {
throw new Exception("the queue is empty");
}
Node<T> popData = this.front; //备份当前node对象

this.front = front.getNext();
popData.setNext(null); //设置队列头节的下一个节点为null,等着GC回收
size --;
if(size == 0) {
rear = front = null;
}
return popData.getData();
}

//获取对头值
public T getFrontData() {
return this.front.getData();
}

//获取队尾值
public T getRearData() {
return this.rear.getData();
}

//判断队列是否为空
public boolean isEmpty() {
return (front == null && rear == null) ? true: false;
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM