在Java中,可以使用以下几种数据结构来实现先进先出(FIFO)的特性:
import java.util.LinkedList;
import java.util.Queue;
public class FIFOQueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// 入队操作
queue.add("A");
queue.add("B");
queue.offer("C");
// 出队操作
String element = queue.remove(); // A
System.out.println(element);
String peekElement = queue.peek(); // B
System.out.println(peekElement);
}
}
import java.util.LinkedList;
public class FIFOStackExample {
public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<>();
// 入栈操作
stack.push("A");
stack.push("B");
stack.push("C");
// 出栈操作
String element = stack.pop(); // C
System.out.println(element);
String peekElement = stack.peek(); // B
System.out.println(peekElement);
}
}
public class FIFODynamicArray {
private int[] array;
private int head;
private int tail;
private int size;
public FIFODynamicArray(int capacity) {
array = new int[capacity];
head = 0;
tail = 0;
size = 0;
}
public void enqueue(int element) {
if (size == array.length) {
throw new IllegalStateException("Queue is full");
}
array[tail] = element;
tail = (tail + 1) % array.length;
size++;
}
public int dequeue() {
if (size == 0) {
throw new IllegalStateException("Queue is empty");
}
int element = array[head];
head = (head + 1) % array.length;
size--;
return element;
}
public boolean isEmpty() {
return size == 0;
}
}