The queue is a fundamental data container in which are the stored elements removed (polled) in the same order as they were inserted into the structure (enqueued). This principle is called FIFO – first in, first out. The opposite approach LIFO – last in, fist out – is used in the stack data structure.
A special type of a queue is a priority queue, in which are the elements polled in the order defined by their priority.
Typical operations
- addLast (enqueue) – Put the element into the queue.
- deleteFirst (poll, dequeue) – Get and remove the first element (head) of the queue.
- getFirst (peek) – Get the first element of the queue.
- isEmpty – Query whether the queue does not contain any element.
- size – Return the number of contained elements.
Usage
In computer science the queue is widely used, for example in these applications:
- Synchronization primitive in multi-threaded applications
- Unix pipe operator used for interprocess communication
- Circular buffer – buffer for data streams
- Heapsort – a sorting algorithm based on a priority queue
Code
01.
/**
02.
* Queue - implemented as a linked list
03.
*/
04.
public
class
Queue {
05.
private
Node first;
06.
private
Node last;
07.
private
int
size;
08.
public
Queue() {
09.
this
.size =
0
;
10.
}
11.
12.
/**
13.
* Insert the element at the end of the queue
14.
* @param i element
15.
*/
16.
public
void
addLast(
int
i) {
17.
Node n =
new
Node(i);
18.
if
(getSize() ==
0
) {
19.
this
.first = n;
20.
this
.last = n;
21.
}
else
{
22.
this
.last.next = n;
23.
this
.last = n;
24.
}
25.
size++;
26.
}
27.
28.
/**
29.
* Remove the first element
30.
* @return element
31.
*/
32.
public
int
deteteFirst() {
33.
if
(getSize() ==
0
)
throw
new
IllegalStateException(
"Queue is empty"
);
34.
int
value = first.value;
35.
first = first.next;
36.
size--;
37.
return
value;
38.
}
39.
/**
40.
* Return the first element
41.
* @return element
42.
*/
43.
public
int
getFirst() {
44.
if
(getSize() ==
0
)
throw
new
IllegalStateException(
"Queue is empty"
);
45.
return
first.value;
46.
}
47.
/**
48.
* Get number of contained elements
49.
* @return lenght of the queue
50.
*/
51.
public
int
getSize() {
52.
return
size;
53.
}
54.
55.
/**
56.
* Query, whether is the queue empty
57.
* @return true if the queue is empty, false otherwise
58.
*/
59.
public
boolean
isEmpty() {
60.
return
this
.size ==
0
;
61.
}
62.
63.
@Override
64.
public
String toString() {
65.
StringBuilder builder =
new
StringBuilder();
66.
Node curr = first;
67.
for
(
int
i =
0
; i <
this
.size; i++) {
68.
builder.append(curr.value).append(
" "
);
69.
curr = curr.next;
70.
}
71.
return
builder.toString();
72.
}
73.
74.
/**
75.
* Inner representation of the element (node of the linked list)
76.
*/
77.
private
class
Node {
78.
private
int
value;
79.
private
Node next;
80.
private
Node(
int
value) {
81.
this
.value = value;
82.
}
83.
}
84.
}