java 自己实现一个queue
时间: 2023-05-04 14:01:59 浏览: 72
队列(Queue)是一种先进先出(First In First Out,FIFO)的数据结构,其中最先进入的元素会被最先处理。在Java中,我们可以通过自己实现一个队列来更好地理解它的内部原理。
Java中的队列可以使用数组或链表来实现,这里我们选择链表实现队列。首先,我们定义一个Node类:
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
其中,data表示结点存储的数据,next表示链表中下一个结点的引用。
然后,我们定义一个Queue类,并定义一些基本操作方法:
class Queue {
Node head;
Node tail;
int size;
public Queue() {
this.head = null;
this.tail = null;
this.size = 0;
}
public boolean isEmpty() {
return head == null;
}
public int size() {
return size;
}
public int peek() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
return head.data;
}
public void add(int data) {
Node newNode = new Node(data);
if (tail != null) {
tail.next = newNode;
}
tail = newNode;
if (head == null) {
head = newNode;
}
size++;
}
public int remove() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
int data = head.data;
head = head.next;
if (head == null) {
tail = null;
}
size--;
return data;
}
}
在队列中,head表示队首,tail表示队尾。size表示队列中元素的数量。isEmpty方法用于判断队列是否为空;size方法用于获取队列中元素的数量;peek方法用于返回队首元素的值,但不删除;add方法用于向队列中添加元素;remove方法用于删除队首元素,并返回其值。
在实现完毕Queue类后,我们可以使用以下代码来测试它:
Queue q = new Queue();
q.add(1);
q.add(2);
q.add(3);
System.out.println(q.peek()); // 输出1
System.out.println(q.size()); // 输出3
System.out.println(q.remove()); // 输出1
System.out.println(q.peek()); // 输出2
System.out.println(q.size()); // 输出2
以上就是一个简单的Java队列的实现方法。通过实现一个队列,我们可以更好地理解队列的原理,进而更好地应用于实际开发中。