在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;
}
}