Java Data Structure Cheat Sheet - Queue
Queue is an interface in Java.
There are multiple implementation choices, but using LinkedList is common and performs as the usual queue as expected.
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
Main methods are:
- boolean add(E e)
- E element()
- E remove()
and there exists the alternative ones as:
- boolean offer(E e)
- E peek()
- E poll()
The first group throws an Exception whereas the second one returns "special value".
They are all O(1).
Example
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(1); // or q.offer(1)
q.add(2);
q.add(3);
System.out.println(q.element()); // 1. you can also use q.peek()
while (!q.isEmpty()) { // isEmpty() is from Collection
int n = q.remove(); // or q.poll()
System.out.println(n); // 1, 2, 3
}
}
}
Comments
Post a Comment