如何使用Java函数创建队列数据结构?
发布时间:2023-07-06 08:28:07
在Java中,可以使用内置的LinkedList类或ArrayDeque类来创建队列数据结构。下面是基于这两个类的示例代码:
1. 使用LinkedList类创建队列数据结构:
import java.util.LinkedList;
public class QueueExample {
private LinkedList<Integer> queue;
public QueueExample() {
queue = new LinkedList<>();
}
public void enqueue(int item) {
queue.addLast(item);
}
public int dequeue() {
return queue.removeFirst();
}
public int peek() {
return queue.getFirst();
}
public boolean isEmpty() {
return queue.isEmpty();
}
public int size() {
return queue.size();
}
public static void main(String[] args) {
QueueExample queueExample = new QueueExample();
queueExample.enqueue(10);
queueExample.enqueue(20);
System.out.println("Size of queue: " + queueExample.size());
System.out.println("Front element of queue: " + queueExample.peek());
System.out.println("Dequeued element: " + queueExample.dequeue());
System.out.println("Size of queue after dequeue: " + queueExample.size());
System.out.println("Is the queue empty? " + queueExample.isEmpty());
}
}
在这个例子中,我们使用LinkedList类的addLast()方法向队列末尾添加元素,使用removeFirst()方法删除队列的 个元素,使用getFirst()方法返回队列的 个元素以及使用isEmpty()和size()方法检查队列是否为空,以及队列的大小。
2. 使用ArrayDeque类创建队列数据结构:
import java.util.ArrayDeque;
public class QueueExample {
private ArrayDeque<Integer> queue;
public QueueExample() {
queue = new ArrayDeque<>();
}
public void enqueue(int item) {
queue.addLast(item);
}
public int dequeue() {
return queue.pollFirst();
}
public int peek() {
return queue.peekFirst();
}
public boolean isEmpty() {
return queue.isEmpty();
}
public int size() {
return queue.size();
}
public static void main(String[] args) {
QueueExample queueExample = new QueueExample();
queueExample.enqueue(10);
queueExample.enqueue(20);
System.out.println("Size of queue: " + queueExample.size());
System.out.println("Front element of queue: " + queueExample.peek());
System.out.println("Dequeued element: " + queueExample.dequeue());
System.out.println("Size of queue after dequeue: " + queueExample.size());
System.out.println("Is the queue empty? " + queueExample.isEmpty());
}
}
在这个例子中,我们使用ArrayDeque类的addLast()方法来向队列末尾添加元素,使用pollFirst()方法删除队列的 个元素,使用peekFirst()方法返回队列的 个元素以及使用isEmpty()和size()方法检查队列是否为空,以及队列的大小。
无论使用LinkedList类还是ArrayDeque类,都可以完成队列的基本操作,如入队、出队、获取队首元素等。具体使用哪个类取决于您的具体需求和偏好。
