79 lines
1.7 KiB
Java
79 lines
1.7 KiB
Java
import java.util.AbstractQueue;
|
|
import java.util.Iterator;
|
|
import java.util.NoSuchElementException;
|
|
import java.util.Queue;
|
|
|
|
public class FileChainee<E> extends AbstractQueue<E> implements Queue<E> {
|
|
private static class Node<E> {
|
|
E data;
|
|
Node<E> next;
|
|
|
|
Node(E data) {
|
|
this.data = data;
|
|
}
|
|
}
|
|
|
|
private Node<E> head; // Premier élément de la file
|
|
private Node<E> tail; // Dernier élément de la file
|
|
private int size = 0; // Taille de la file
|
|
|
|
@Override
|
|
public boolean offer(E element) {
|
|
Node<E> newNode = new Node<>(element);
|
|
if (head == null) {
|
|
tail = newNode;
|
|
} else {
|
|
newNode.next = head;
|
|
}
|
|
head = newNode;
|
|
size++;
|
|
return true;
|
|
}
|
|
|
|
@Override
|
|
public E poll() {
|
|
if (isEmpty()) {
|
|
return null;
|
|
}
|
|
E data = head.data;
|
|
head = head.next;
|
|
if (head == null) {
|
|
tail = null;
|
|
}
|
|
size--;
|
|
return data;
|
|
}
|
|
|
|
@Override
|
|
public E peek() {
|
|
return (head == null) ? null : head.data;
|
|
}
|
|
|
|
@Override
|
|
public Iterator<E> iterator() {
|
|
return new Iterator<>() {
|
|
private Node<E> current = head;
|
|
|
|
@Override
|
|
public boolean hasNext() {
|
|
return current != null;
|
|
}
|
|
|
|
@Override
|
|
public E next() {
|
|
if (!hasNext()) {
|
|
throw new NoSuchElementException();
|
|
}
|
|
E data = current.data;
|
|
current = current.next;
|
|
return data;
|
|
}
|
|
};
|
|
}
|
|
|
|
@Override
|
|
public int size() {
|
|
return size;
|
|
}
|
|
}
|