You can use the linked list as a queue (not a LinkedList, but your own implementation).
To add a new item, you need to create a new instance of the queue class, set its start item to the copied queue run item, and create a new end item.
Removing an item is similar, but set the end element of the new queue to the second so that the last element of the copied queue.
The queue class may look like this:
static class Node {
final Node next;
final Object o;
Node(Node next, Object o) {...}
}
final Node start, end;
private Queue(Node start, Node end) {...}
public Queue(Object o) {
start = end = new Node(null, o);
}
public Queue add(Object o) {
return new Queue(start, new Node(end, o));
}
public Queue remove() {
return new Queue(start, end.next);
}
The complexity of the methods of the queue addand removeis equal to O (1).
Please note that you can iterate over this queue only in reverse order (i.e. latest elements). Perhaps you can come up with something that can be repeated differently or even in both directions.
source
share