SlideShare a Scribd company logo
1 of 65
Download to read offline
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Queues
Queues page 2
© Dr. Jonathan (Yahya) Cazalas
Queues – An Overview
 Queues:
 Like stacks, Queues are an Abstract Data Type
 They are NOT built into the core feature set of JAVA
 We must define them and their behaviors
 So what is a queue?
 A data structure that stores information in the form of a
typical waiting line
 New items are added at the end of the queue
 Elements are removed from the front of the queue
 So unlike a stack
 A queue is accessible from both ends (front and end)
Queues page 3
© Dr. Jonathan (Yahya) Cazalas
Queues – An Overview
 Queues:
 Access Policy:
 The first element that is inserted into the queue is the first
element that will leave the queue
 Therefore, in order for the last element to leave the queue, it
must wait until all elements preceding it are removed
 Known as the “First in, First out” access policy
 FIFO for short
 Real life example: waiting in line to be served
 When a customer arrives, they enter the line at the back
 They wait their turn
 Finally, they get to the front, are served, and exit the line
Queues page 4
© Dr. Jonathan (Yahya) Cazalas
Queues – An Overview
 Queues:
 Basic Operations:
 enqueue:
 Inserts and element at the end of the queue
 O(1) time
 dequeue:
 Removes the element at the front of the queue
 O(1) time
 peek:
 Looks at the element at the front of the queue without actually
removing it
 O(1) time
Queues page 5
© Dr. Jonathan (Yahya) Cazalas
Queues – An Overview
 Queues:
 Basic Operations:
 isEmpty:
 Checks to see if the queue is empty
 O(1) time
 isFull:
 Checks to see if the queue is full
 O(1) time
 clear:
 Clears the contents of the queue
 In “queue” order
 From front to back
 O(n) time
Queues page 6
© Dr. Jonathan (Yahya) Cazalas
front
START: 2 4 6 8 10
Q
rear
Sequence of operations
Time Operation
1 enqueue(12)
2 dequeue
3 enqueue(14)
4 enqueue(16)
5 dequeue
time 1: 2 4 6 8 10 12
time 2: 4 6 8 10 12
time 3:
4 6 8 10 12 14
time 4: 4 6 8 10 12 14 16
time 5: 6 8 10 12 14 16
FIFO Nature of a Queue
Queues page 7
© Dr. Jonathan (Yahya) Cazalas
Queues: Implementation in JAVA
 Implementation of Queues in JAVA:
 As with Stacks, there are two obvious ways to
implement Queues :
1) Using arrays
2) Using linked lists
 We will go over both…
Queues page 8
© Dr. Jonathan (Yahya) Cazalas
Queues: Implementation in JAVA
 Implementation of Queues in JAVA:
 Array:
 We will implement the queue as an array!
 What does this mean?
 This means that when you examine the code for the queue, in
fact, it is simply using an array!
 So then how is the array a queue? What makes it a
queue?
 The BEHAVIOR!
 We said that an Abstract Data Type is defined based on
its behaviors (the operations it can perform).
 So we will restrict the behavior of the array.
 We will make the array behave like (act like) a queue!
Queues page 9
© Dr. Jonathan (Yahya) Cazalas
Queues: Implementation in JAVA
 Implementation of Queues in JAVA:
 Array:
 So we will restrict the behavior of the Queue.
 We will make the array behave like (act like) a queue!
 Example:
 With an array, you can insert anywhere or delete anywhere
 Insert at the beginning, middle, or end…anywhere!
 However:
 Since we are making this array behave like (act like) a queue:
 We will ONLY allow insertion at the “back”
 ENQUEUE
 We will ONLY allow deletion at the “front”
 DEQUEUE
 So now, our array has basically transformed into a queue!
Queues page 10
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation
 Queues:
 Array Implementation:
 How would you implement a queue using an array?
 Think of what “stuff” you would need…
 Other than the actual array, what else do you need?
 Remember, you need to enqueue and dequeue
 Meaning:
 You need to ALWAYS know where the front and back of the
queue are.
Queues page 11
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation
 Queues:
 Here is our class, QueueArray:
class QueueArray {
private int[] queue;
private int front;
private int rear; // not actually needed
// Constructor and Methods here
}
Queues page 12
© Dr. Jonathan (Yahya) Cazalas
Sequence of operations
Time Operation
1 dequeue
2 enqueue(12)
3 dequeue
4 dequeue
5 dequeue
6 dequeue
7 dequeue
front
time 5:
rear
10 12
front
start: 2 4 6 8 10
Q
rear
front
time 1: 4 6 8 10
rear
front
time 3: 6 8 10 12
rear
front
time 4: 8 10 12
rear
Notice that the
array now has
room to add
elements to the
queue.
time 2:
front
4 6 8
rear
10 12
Queues: Array Implementation
“brute force” method
Queues page 13
© Dr. Jonathan (Yahya) Cazalas
front
time 5:
rear
10 12
front
start: 2 4 6 8 10
Q
rear
Queues: Array Implementation
front/rear
time 6: 12
front
time 7:
rear
“brute force” method
Sequence of operations
Time Operation
1 dequeue
2 enqueue(12)
3 dequeue
4 dequeue
5 dequeue
6 dequeue
7 dequeue
Queues page 14
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation
 Queues:
 What is wrong with the last example?
 enqueues run in O(1) time.
 This is a GOOD thing!
 But look at the dequeue
 How long does a dequeue take?
 The dequeue itself takes O(1) time
 However, after the first node is removed, ALL nodes, that
remain in the queue after the dequeue, must be moved
forward one position in the array
 Possibly n elements have to move after one dequeue
 This is O(n) time per deletion!
 And we know, conceptually, a dequeue should be O(1)
“brute force” method
Queues page 15
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (2)
 Queues:
 How can we do better?
 Well, we want to avoid moving all items when a
dequeue occurs
 But if we don’t move the individual elements…
 What must we do?
 We MUST move the front and back “pointers” to those
items
 An example makes this clear…
Queues page 16
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (2)
front
time 5:
rear
10 12
front
time 2:
rear
4 6 8 10 12
front
start: 2 4 6 8 10
Q
rear
front
time 1: 4 6 8 10
rear
front
time 3: 6 8
rear
10 12
front
time 4: 8
rear
10 12
Notice that the
queue now
appears to be full
even though there
are locations
available in the
array!
Sequence of operations
Time Operation
1 dequeue
2 enqueue(12)
3 dequeue
4 dequeue
5 dequeue
6 dequeue
7 dequeue
Queues page 17
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (2)
front
time 5:
rear
10 12
front
start: 2 4 6 8 10
Q
rear
time 6:
front/rear
12
front
time 7:
rear
Even Worse:
The queue now
appears full even
though there are
NO items in the
array!
Sequence of operations
Time Operation
1 dequeue
2 enqueue(12)
3 dequeue
4 dequeue
5 dequeue
6 dequeue
7 dequeue
Queues page 18
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (2)
 Queues:
 What is wrong with the last example?
 The problem: we end up with wasted cells
 As the front moves towards the rear (when dequeues
occur), we have empty, useless cells in the array
 So we avoided the n moves when we dequeue
 We did so by simply moving the reference to front
 But in the process we have wasted space
 How can we do better?
 We view the array as if it were circular
Queues page 19
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (3)
 Queues:
 Circular Array Implementation
 Circular arrays are a very common way of implementing
an array-based queue
 What is a circular array?
 It is a regular array
 We simply “view” it as being circular
 In a circular implementation, the queue is considered to
be full whenever the front of the queue immediately
precedes the rear of the queue in the counterclockwise
direction.
 The examples on the following pages should help you to
visualize a “circular” array.
Queues page 20
© Dr. Jonathan (Yahya) Cazalas
2 15 11 10 6 8
4
front rear
normal array implementation: queue is full
6 8 4 2 15 11
10
front
rear
circular array implementation: queue is full
15
2
4
8
6
10
11
rear front
visualization of a queue
implemented as a circular array
Queues: Array Implementation (3)
Queues page 21
© Dr. Jonathan (Yahya) Cazalas
Queues: Array Implementation (3)
 Queues:
 Circular Array Implementation
 This implementation allows us to keep the elements in
their respective “cells” of the array
 We don’t need to move n elements during dequeues
 AND we also don’t have wasted space!
 The circular “view” of the array allows us to “wrap”
around the array
 Assume the length of the array is SIZE
 It is NOT the case that the rear most stop at index[SIZE-1]
 meaning, the last element
 Rather, since the array wraps around, the front could be at a
greater index than the index of the rear!
Queues page 22
© Dr. Jonathan (Yahya) Cazalas
Queues: Circular Array
Implementation
 Queues:
 Circular Array Implementation
 The next several slides illustrate the operation of a
circular array based implementation of a queue.
 The normal implementation (brute-force) is also shown
for comparative purposes.
 However, remember that the brute force method is
extremely inefficient due to the amount of data
movement required by dequeue operations.
Queues page 23
© Dr. Jonathan (Yahya) Cazalas
Queues: Circular Array
Implementation
 Queues:
 Circular Array Implementation
 The scenario begins at some point in time before which
other enqueue and dequeue operations have occurred
on the queue.
 Our scenario begins with some elements already in the
queue.
 As you can see on the next page, these elements were
enqueued in the order of: 2, 4, and 8.
 The scenario continues by enqueuing 6, enqueuing 10,
dequeue, enqueuing 18, dequeue, dequeue, dequeue,
enqueuing 9, dequeue, dequeue, and finally one last
dequeue which empties the queue at this point.
Queues page 24
© Dr. Jonathan (Yahya) Cazalas
visualization of a queue
implemented as a circular array
after insertion of element 6
6
4
2
rear
front
8
Enqueue element 6
4 8
2
front rear
before
normal array implementation
4 8 6
2
front rear
after
2 4 8
front rear
before
circular array implementation
2 4 8 6
front rear
after
Queues: Circular Array
Implementation
Queues page 25
© Dr. Jonathan (Yahya) Cazalas
Enqueue element 10
4 8 6
2
front rear
before
normal array implementation
4 8 6 10
2
front rear
after
2 4 8 6
front rear
before
circular array implementation
2 4 8 6
10
front
rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after insertion of element 10
6
4
2
rear
front
8
10
Queues page 26
© Dr. Jonathan (Yahya) Cazalas
dequeue
4 8 6 10
2
front rear
before
normal array implementation
8 6 10
4
front rear
after
2 4 8 6
10
front
rear
before
circular array implementation
4 8 6
10
front
rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
6
4
rear
front
8
10
Queues page 27
© Dr. Jonathan (Yahya) Cazalas
Enqueue element 18
8 6 10
4
front rear
before
normal array implementation
8 6 10 18
4
front rear
after
4 8 6
10
front
rear
before
circular array implementation
18 4 8 6
10
front
rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after insertion of element 18
6
4
rear
front
8
10
18
Queues page 28
© Dr. Jonathan (Yahya) Cazalas
dequeue
8 6 10 18
4
front rear
before
normal array implementation
6 10 18
8
front rear
after
18 4 8 6
10
front
rear
before
circular array implementation
18 8 6
10
front
rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
6
rear
front
8
10
18
Queues page 29
© Dr. Jonathan (Yahya) Cazalas
dequeue
6 10 18
8
front rear
before
normal array implementation
10 18
6
front rear
after
18 8 6
10
front
rear
before
circular array implementation
18 6
10
front
rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
6
rear
front
10
18
Queues page 30
© Dr. Jonathan (Yahya) Cazalas
dequeue
10 18
6
front rear
before
normal array implementation
18
10
front rear
after
18 6
10
front
rear
before
circular array implementation
18
10
front rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
rear
front
10
18
Queues page 31
© Dr. Jonathan (Yahya) Cazalas
Enqueue element 9
18
10
front rear
before
normal array implementation
18 9
10
front rear
after
18
10
front rear
before
circular array implementation
18 9
10
front rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after insertion of element 9
rear
front
10
18
9
Queues page 32
© Dr. Jonathan (Yahya) Cazalas
dequeue
18 9
10
front rear
before
normal array implementation
9
18
front rear
after
18 9
10
front rear
before
circular array implementation
18 9
front rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
rear
front
18
9
Queues page 33
© Dr. Jonathan (Yahya) Cazalas
dequeue
9
18
front rear
before
normal array implementation
9
front/rear
after
18 9
front rear
before
circular array implementation
9
front/rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
rear
front
9
Queues page 34
© Dr. Jonathan (Yahya) Cazalas
dequeue – queue empties!
9
front/rear
before
normal array implementation
front/rear
after
9
front/rear
before
circular array implementation
front/rear
after
Queues: Circular Array
Implementation
visualization of a queue
implemented as a circular array
after dequeue operation
rear
front
Queues page 35
© Dr. Jonathan (Yahya) Cazalas
 Queues:
 Circular Array Implementation
 So this works great in pictures
 But think about something…
 How did we modify the position (index) of front and rear?
 Did we just increment the front/rear indices as needed?
 Meaning, did we simply increment the index of rear every time
an enqueue occurs?
 And did we simply increment the index of front every time a
dequeue occurs?
 In a normal array, this is fine.
 However, this is a circular array, and we must pay attention!
 Simply incrementing will not cut it!
Queues: Circular Array
Implementation
Queues page 36
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 How did we modify the position (index) of front and rear?
 Ex: suppose we have the situation below (also from page 34)
 If we dequeue, the front will need to refer to the ‘10’ in index 0!
 So how do we make this happen?
 Can we simply increment front?
 No, we cannot, as that would be out of bounds!
Queues: Circular Array
Implementation
18 6
10
front
rear
before
Queues page 37
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 How did we modify the position (index) of front and rear?
 One possible solution: use an if/else statement
 If the front is currently equal to “queue.length – 1”
 Meaning, if the front is currently at the last index of the array
 And if we are performing a dequeue
 Then, the *new* front index will need to be set to index 0.
 Else, simply increment front.
 Of course, either way, we need to RETURN the value that was
at the front index (because this is a dequeue operation).
Queues: Circular Array
Implementation
18 6
10
front
rear
before
Queues page 38
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 How did we modify the position (index) of front and rear?
 Here is the code:
Queues: Circular Array
Implementation
18 6
10
front
rear
before
public int dequeue() {
int temp = queue[front];
if (front == queue.length - 1)
front = 0; // set the new front to zero
else
front++; // just increment the front
// Finally, return the value that was at front
return temp;
}
Queues page 39
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 The last solution does work…but it has a branch operation
 Meaning, it has an if/else statement.
 This is fine, but branching operations can be slow
 Instead of using an if/else statement to recalculate the position
of front, consider the following…
 front = (front + 1) % queue.length;
 So on our example, (6 + 1) % 7 = 0
 This is PRECISELY the index we want!
 The new front is calculated as index 0.
Queues: Circular Array
Implementation
18 6
10
front
rear
before
The ‘7’ here refers to
the size of the array
Queues page 40
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 The last solution does work…but it has a branch operation
 Meaning, it has an if/else statement.
 So how do we get front to “point” to index 0?
 We need to use mod (%)!
 We increment front and then mod it by the queue size
 front = (front + 1) % queue.length;
 So now the new front refers to index 0.
 This is PRECISELY the index we wanted!
Queues: Circular Array
Implementation
18 6
10
front
rear
before
Queues page 41
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Dequeue Operation
 New Solution using mod (%):
 Here is the code:
Queues: Circular Array
Implementation
18 6
10
front
rear
before
public int dequeue() {
int temp = queue[front];
// Now update the location of front using mod
front = (front+1) % queue.length;
// decrement numItems (you will see why we use numItems)
numItems--;
// And finally, return temp...the value we dequeued
return temp;
}
Queues page 42
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 We do NOT need to save the index for the rear.
 Why?
 Because if we know the index to the front
 AND if we know the number of elements
 we can quickly determine the new enqueue position
 Ex: let’s say front was at index 7 and there are 2 elements
 This means the rear would be at index 8
 And the NEW enqueue position would be index 9
 So we see that the NEW enqueue position is found by simply
adding the index of the front and the number of elements
 But we need to take care of wraparound…
Queues: Circular Array
Implementation
Queues page 43
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Assume we have a queue of size 10
 From index 0 to index 9
 The front is currently index 4
 And there are 6 elements already in the queue
 And the next operation is enqueue(g)
 Remember, enqueue is a method that we write in the program
 So this ‘g’ is sent over to the enqueue method as “char val”
Queues: Circular Array
Implementation
a b c
front
d f
e
Queues page 44
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Assume we have a queue of size 10
 From index 0 to index 9
 The front is currently index 4
 And there are 6 elements already in the queue
 We know that the next enqueue will go at index 0
 But how do we do this?
 One solution: if/else statement
Queues: Circular Array
Implementation
a b c
front
d f
e
g
Queues page 45
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Assume we have a queue of size 10
 The front is currently index 4
 numItems is currently 6 (values a to f)
 IF (front+numItems) equals the size of the array
 Meaning if (front+numItems == queue.length)
 This means that the NEW enqueue position must be at index 0!
 So we will save the new enqueue value at index 0.
 Else, just save the new enqueue value at the next position
available by incrementing
Queues: Circular Array
Implementation
a b c
front
d f
e
g
Queues page 46
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Assume we have a queue of size 10
 The front is currently index 4
 numItems is currently 6 (values a to f)
 Here is the code:
Queues: Circular Array
Implementation
a b c
front
d f
e
g
public void enqueue(int value) {
if ((front+numItems) == queue.length)
queue[0] = value;
else
queue[(front+numItems)] = value;
numItems++; // Finally, increment numItems
}
Queues page 47
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Again, the last solution does work…but it has a branch
 Which is a slow operation.
 Instead, we can again use mod (%).
 We know that the next enqueue will go at index 0
 But how do we do this in code (using mod)?
 queue[(front + numItems)%queue.length] = value;
 So for our example:
 queue[(4 + 6) % 10] = value;
 queue[0] = a … so the value ‘a’ get saved into index 0!
Queues: Circular Array
Implementation
a b c
front
d f
e
g
Queues page 48
© Dr. Jonathan (Yahya) Cazalas
 Queues (Circular Array Implementation):
 Enqueue Operation
 Again, the last solution does work…but it has a branch
 Which is a slow operation.
 Instead, we can again use mod (%).
 Here is the code:
Queues: Circular Array
Implementation
a b c
front
d f
e
g
public void enqueue(int value) {
queue[(front+numItems) % queue.length] = value;
numItems++;
}
Queues page 49
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: Summer in Saudi
Queues page 50
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Implementation of Queues in JAVA:
 Linked-List:
 We will implement the queue as a Linked-List!
 What does this mean?
 This means that when you examine the code for the queue, in
fact, it is simply using a Linked-List!
 So then how is the Linked-List a queue? What makes it a
queue?
 The BEHAVIOR!
 We said that an Abstract Data Type is defined based on
its behaviors (the operations it can perform).
 So we will restrict the behavior of the Linked-List.
 We will make the Linked-List behave like (act like) a queue!
Queues page 51
© Dr. Jonathan (Yahya) Cazalas
 Implementation of Queues in JAVA:
 Linked-List :
 So we will restrict the behavior of the Queue.
 We will make the Linked-List behave like (act like) a queue!
 Example:
 With a Linked-List, you can insert or delete anywhere
 Insert at the beginning, middle, or end…anywhere!
 However:
 Since we are making this Linked-List behave like a queue:
 We will ONLY allow insertion at the “back”
 ENQUEUE
 We will ONLY allow deletion at the “front”
 DEQUEUE
 So now, our Linked-List has transformed into a queue!
Queues: Linked-List Implementation
Queues page 52
© Dr. Jonathan (Yahya) Cazalas
 Queues:
 Linked-list implementation
 Think of how this will work.
 You need to know where is the front and where is the
back.
 So where do you want the front of the queue to be?
 Do you want it to be the head of the list?
 Or do you want it to be the tail/rear of the list?
 The choice is yours!
 Let us make the front of the queue as the head of the list.
 And the rear will simply be the location of the last node.
Queues: Linked-List Implementation
Queues page 53
© Dr. Jonathan (Yahya) Cazalas
 Queues:
 Linked-list implementation
 Dequeue:
 Remember, the front of the queue is the head of the list.
 Therefore, when we dequeue, this means we will simply
perform a delete command from the FRONT of the linked
list.
 This is very easy to do…we simply make front point to
front.next!
 front = front.getNext();
 There are a few other things to consider as well
 See the QueueLL.java code given on the website.
Queues: Linked-List Implementation
Queues page 54
© Dr. Jonathan (Yahya) Cazalas
 Queues:
 Linked-list implementation
 Enqueue:
 Now consider enqueue. How will you enqueue the next
item into the queue?
 Well, you need to know where is the current last item.
 One solution…traverse each time to the current last item.
 And then enqueue the new item afterwards.
 This would be very slow!
 Every time you want to enqueue, you would have to
traverse your entire list.
 What if the list was huuuuuuuge?
Queues: Linked-List Implementation
Queues page 55
© Dr. Jonathan (Yahya) Cazalas
 Queues:
 Linked-list implementation
 Enqueue:
 Better solution: used a tail/back pointer
 Meaning inside the QueueLL.java code, you will always
maintain (keep) a reference to the last node
 So this class will have two important variables:
 private QueueNode front;
 private QueueNode back;
 Both of these variables need to be updated whenever
enqueue and dequeue operations are performed
 See code on website for more details.
Queues: Linked-List Implementation
Queues page 56
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
 Therefore:
 An enqueue is simply inserting into the back of the
linked list!
 This is very easy because we keep a pointer to the last node.
 It only requires changing two references!
 A dequeue would be deleting the front node
 Again, the easiest type of deletion
 Only requiring changing two references!
 So, in fact, a linked-list version of a queue is EASIER to
code than a regular linked list!
Queues page 57
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
 So each node will be an element of the queue
 Each node has a data value
 Each node also has a next
 We simply enqueue (insert at back)
 And dequeue (delete the front node)
Queues page 58
© Dr. Jonathan (Yahya) Cazalas
 Linked Lists Implementation of Queues:
 So we will create two classes (like Linked-Lists)
 QueueNode.java (this is like the LLnode class)
 QueueLL.java (this is like the LinkedList class)
 We use most of the SAME methods as used for
the Linked List class
 However, we RESTRICT the functionality
 Now, we cannot insert anywhere in the list
 We can only insert at the back (enqueue)
 Now, we cannot delete from anywhere in the list
 We can only delete from the front (dequeue)
Queues: Linked-List Implementation
Queues page 59
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
 Code for QueueNode.java
public class QueueNode {
private int data;
private QueueNode next;
// CONSTRUCTORS
public QueueNode() {
data = 0;
next = null;
}
public QueueNode(int data) {
this.data = data;
next = null;
}
public QueueNode(int data, QueueNode next) {
this.data = data;
this.next = next;
}
Queues page 60
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
...
// ACCESSORS
public int getData() {
return data;
}
public QueueNode getNext() {
return next;
}
// MUTATORS
public void setData(int data) {
this.data = data;
}
public void setNext(QueueNode next) {
this.next = next;
}
}
Queues page 61
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
 Code for QueueLL.java (similar to LinkedList.java)
public class QueueLL {
// top: reference variable to the top of the stack
// (same as "head" of linked list)
private QueueNode front;
private QueueNode back;
// CONSTRUCTOR
public QueueLL() {
front = null;
back = null;
}
// MANY methods go here to control the stack
// POP, PUSH, TOP and more...
Queues page 62
© Dr. Jonathan (Yahya) Cazalas
Queues: Linked-List Implementation
 Linked Lists Implementation of Queues:
 Code for QueueLL.java (similar to LinkedList.java)
 dequeue() method:
// QueueNode | dequeue()
public QueueNode dequeue() {
QueueNode temp = front;
front = dequeue(front);
if (front == null)
back = null;
return temp;
}
// QueueNode | dequeue(QueueNode)
private QueueNode dequeue(QueueNode front) {
front = front.getNext();
return front;
}
Queues page 63
© Dr. Jonathan (Yahya) Cazalas
Queues
WASN’T
THAT
SUPERB!
Queues page 64
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Queues

More Related Content

What's hot

What's hot (20)

Data structures
Data structuresData structures
Data structures
 
Java vs JavaScript | Edureka
Java vs JavaScript | EdurekaJava vs JavaScript | Edureka
Java vs JavaScript | Edureka
 
Instruction scheduling
Instruction schedulingInstruction scheduling
Instruction scheduling
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
 
Operating system - Deadlock
Operating system - DeadlockOperating system - Deadlock
Operating system - Deadlock
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Heap sort
Heap sortHeap sort
Heap sort
 
Java Applets
Java AppletsJava Applets
Java Applets
 
OS - Deadlock
OS - DeadlockOS - Deadlock
OS - Deadlock
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Exception handling
Exception handling Exception handling
Exception handling
 
JAVA APPLET BASICS
JAVA APPLET BASICSJAVA APPLET BASICS
JAVA APPLET BASICS
 
Introduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their featuresIntroduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their features
 
Merge sort
Merge sortMerge sort
Merge sort
 
Operating system concepts
Operating system conceptsOperating system concepts
Operating system concepts
 
Space Complexity in Data Structure.docx
Space Complexity in Data Structure.docxSpace Complexity in Data Structure.docx
Space Complexity in Data Structure.docx
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 

Similar to queues (20)

Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
 
Lecture 2d queues
Lecture 2d queuesLecture 2d queues
Lecture 2d queues
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
Queue
QueueQueue
Queue
 
stacks2
stacks2stacks2
stacks2
 
queue.pptx
queue.pptxqueue.pptx
queue.pptx
 
Queue and its operations
Queue and its operationsQueue and its operations
Queue and its operations
 
Queue ADT for data structure for computer
Queue ADT for data structure for computerQueue ADT for data structure for computer
Queue ADT for data structure for computer
 
Unit ii linear data structures
Unit ii linear data structures Unit ii linear data structures
Unit ii linear data structures
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
Unit 5 dsa QUEUE
Unit 5 dsa QUEUEUnit 5 dsa QUEUE
Unit 5 dsa QUEUE
 
stacks1
stacks1stacks1
stacks1
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
2 b queues
2 b queues2 b queues
2 b queues
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Data structure.ppt
Data structure.pptData structure.ppt
Data structure.ppt
 
stack.ppt
stack.pptstack.ppt
stack.ppt
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

More from Mohamed Elsayed (20)

binary_trees4
binary_trees4binary_trees4
binary_trees4
 
binary_trees3
binary_trees3binary_trees3
binary_trees3
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
recursion3
recursion3recursion3
recursion3
 
recursion1
recursion1recursion1
recursion1
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
sorted_listmatch
sorted_listmatchsorted_listmatch
sorted_listmatch
 
binary_search
binary_searchbinary_search
binary_search
 
arrays
arraysarrays
arrays
 
introduction
introductionintroduction
introduction
 
heaps2
heaps2heaps2
heaps2
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 
graphs
graphsgraphs
graphs
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

queues

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Queues
  • 2. Queues page 2 © Dr. Jonathan (Yahya) Cazalas Queues – An Overview  Queues:  Like stacks, Queues are an Abstract Data Type  They are NOT built into the core feature set of JAVA  We must define them and their behaviors  So what is a queue?  A data structure that stores information in the form of a typical waiting line  New items are added at the end of the queue  Elements are removed from the front of the queue  So unlike a stack  A queue is accessible from both ends (front and end)
  • 3. Queues page 3 © Dr. Jonathan (Yahya) Cazalas Queues – An Overview  Queues:  Access Policy:  The first element that is inserted into the queue is the first element that will leave the queue  Therefore, in order for the last element to leave the queue, it must wait until all elements preceding it are removed  Known as the “First in, First out” access policy  FIFO for short  Real life example: waiting in line to be served  When a customer arrives, they enter the line at the back  They wait their turn  Finally, they get to the front, are served, and exit the line
  • 4. Queues page 4 © Dr. Jonathan (Yahya) Cazalas Queues – An Overview  Queues:  Basic Operations:  enqueue:  Inserts and element at the end of the queue  O(1) time  dequeue:  Removes the element at the front of the queue  O(1) time  peek:  Looks at the element at the front of the queue without actually removing it  O(1) time
  • 5. Queues page 5 © Dr. Jonathan (Yahya) Cazalas Queues – An Overview  Queues:  Basic Operations:  isEmpty:  Checks to see if the queue is empty  O(1) time  isFull:  Checks to see if the queue is full  O(1) time  clear:  Clears the contents of the queue  In “queue” order  From front to back  O(n) time
  • 6. Queues page 6 © Dr. Jonathan (Yahya) Cazalas front START: 2 4 6 8 10 Q rear Sequence of operations Time Operation 1 enqueue(12) 2 dequeue 3 enqueue(14) 4 enqueue(16) 5 dequeue time 1: 2 4 6 8 10 12 time 2: 4 6 8 10 12 time 3: 4 6 8 10 12 14 time 4: 4 6 8 10 12 14 16 time 5: 6 8 10 12 14 16 FIFO Nature of a Queue
  • 7. Queues page 7 © Dr. Jonathan (Yahya) Cazalas Queues: Implementation in JAVA  Implementation of Queues in JAVA:  As with Stacks, there are two obvious ways to implement Queues : 1) Using arrays 2) Using linked lists  We will go over both…
  • 8. Queues page 8 © Dr. Jonathan (Yahya) Cazalas Queues: Implementation in JAVA  Implementation of Queues in JAVA:  Array:  We will implement the queue as an array!  What does this mean?  This means that when you examine the code for the queue, in fact, it is simply using an array!  So then how is the array a queue? What makes it a queue?  The BEHAVIOR!  We said that an Abstract Data Type is defined based on its behaviors (the operations it can perform).  So we will restrict the behavior of the array.  We will make the array behave like (act like) a queue!
  • 9. Queues page 9 © Dr. Jonathan (Yahya) Cazalas Queues: Implementation in JAVA  Implementation of Queues in JAVA:  Array:  So we will restrict the behavior of the Queue.  We will make the array behave like (act like) a queue!  Example:  With an array, you can insert anywhere or delete anywhere  Insert at the beginning, middle, or end…anywhere!  However:  Since we are making this array behave like (act like) a queue:  We will ONLY allow insertion at the “back”  ENQUEUE  We will ONLY allow deletion at the “front”  DEQUEUE  So now, our array has basically transformed into a queue!
  • 10. Queues page 10 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation  Queues:  Array Implementation:  How would you implement a queue using an array?  Think of what “stuff” you would need…  Other than the actual array, what else do you need?  Remember, you need to enqueue and dequeue  Meaning:  You need to ALWAYS know where the front and back of the queue are.
  • 11. Queues page 11 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation  Queues:  Here is our class, QueueArray: class QueueArray { private int[] queue; private int front; private int rear; // not actually needed // Constructor and Methods here }
  • 12. Queues page 12 © Dr. Jonathan (Yahya) Cazalas Sequence of operations Time Operation 1 dequeue 2 enqueue(12) 3 dequeue 4 dequeue 5 dequeue 6 dequeue 7 dequeue front time 5: rear 10 12 front start: 2 4 6 8 10 Q rear front time 1: 4 6 8 10 rear front time 3: 6 8 10 12 rear front time 4: 8 10 12 rear Notice that the array now has room to add elements to the queue. time 2: front 4 6 8 rear 10 12 Queues: Array Implementation “brute force” method
  • 13. Queues page 13 © Dr. Jonathan (Yahya) Cazalas front time 5: rear 10 12 front start: 2 4 6 8 10 Q rear Queues: Array Implementation front/rear time 6: 12 front time 7: rear “brute force” method Sequence of operations Time Operation 1 dequeue 2 enqueue(12) 3 dequeue 4 dequeue 5 dequeue 6 dequeue 7 dequeue
  • 14. Queues page 14 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation  Queues:  What is wrong with the last example?  enqueues run in O(1) time.  This is a GOOD thing!  But look at the dequeue  How long does a dequeue take?  The dequeue itself takes O(1) time  However, after the first node is removed, ALL nodes, that remain in the queue after the dequeue, must be moved forward one position in the array  Possibly n elements have to move after one dequeue  This is O(n) time per deletion!  And we know, conceptually, a dequeue should be O(1) “brute force” method
  • 15. Queues page 15 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (2)  Queues:  How can we do better?  Well, we want to avoid moving all items when a dequeue occurs  But if we don’t move the individual elements…  What must we do?  We MUST move the front and back “pointers” to those items  An example makes this clear…
  • 16. Queues page 16 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (2) front time 5: rear 10 12 front time 2: rear 4 6 8 10 12 front start: 2 4 6 8 10 Q rear front time 1: 4 6 8 10 rear front time 3: 6 8 rear 10 12 front time 4: 8 rear 10 12 Notice that the queue now appears to be full even though there are locations available in the array! Sequence of operations Time Operation 1 dequeue 2 enqueue(12) 3 dequeue 4 dequeue 5 dequeue 6 dequeue 7 dequeue
  • 17. Queues page 17 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (2) front time 5: rear 10 12 front start: 2 4 6 8 10 Q rear time 6: front/rear 12 front time 7: rear Even Worse: The queue now appears full even though there are NO items in the array! Sequence of operations Time Operation 1 dequeue 2 enqueue(12) 3 dequeue 4 dequeue 5 dequeue 6 dequeue 7 dequeue
  • 18. Queues page 18 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (2)  Queues:  What is wrong with the last example?  The problem: we end up with wasted cells  As the front moves towards the rear (when dequeues occur), we have empty, useless cells in the array  So we avoided the n moves when we dequeue  We did so by simply moving the reference to front  But in the process we have wasted space  How can we do better?  We view the array as if it were circular
  • 19. Queues page 19 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (3)  Queues:  Circular Array Implementation  Circular arrays are a very common way of implementing an array-based queue  What is a circular array?  It is a regular array  We simply “view” it as being circular  In a circular implementation, the queue is considered to be full whenever the front of the queue immediately precedes the rear of the queue in the counterclockwise direction.  The examples on the following pages should help you to visualize a “circular” array.
  • 20. Queues page 20 © Dr. Jonathan (Yahya) Cazalas 2 15 11 10 6 8 4 front rear normal array implementation: queue is full 6 8 4 2 15 11 10 front rear circular array implementation: queue is full 15 2 4 8 6 10 11 rear front visualization of a queue implemented as a circular array Queues: Array Implementation (3)
  • 21. Queues page 21 © Dr. Jonathan (Yahya) Cazalas Queues: Array Implementation (3)  Queues:  Circular Array Implementation  This implementation allows us to keep the elements in their respective “cells” of the array  We don’t need to move n elements during dequeues  AND we also don’t have wasted space!  The circular “view” of the array allows us to “wrap” around the array  Assume the length of the array is SIZE  It is NOT the case that the rear most stop at index[SIZE-1]  meaning, the last element  Rather, since the array wraps around, the front could be at a greater index than the index of the rear!
  • 22. Queues page 22 © Dr. Jonathan (Yahya) Cazalas Queues: Circular Array Implementation  Queues:  Circular Array Implementation  The next several slides illustrate the operation of a circular array based implementation of a queue.  The normal implementation (brute-force) is also shown for comparative purposes.  However, remember that the brute force method is extremely inefficient due to the amount of data movement required by dequeue operations.
  • 23. Queues page 23 © Dr. Jonathan (Yahya) Cazalas Queues: Circular Array Implementation  Queues:  Circular Array Implementation  The scenario begins at some point in time before which other enqueue and dequeue operations have occurred on the queue.  Our scenario begins with some elements already in the queue.  As you can see on the next page, these elements were enqueued in the order of: 2, 4, and 8.  The scenario continues by enqueuing 6, enqueuing 10, dequeue, enqueuing 18, dequeue, dequeue, dequeue, enqueuing 9, dequeue, dequeue, and finally one last dequeue which empties the queue at this point.
  • 24. Queues page 24 © Dr. Jonathan (Yahya) Cazalas visualization of a queue implemented as a circular array after insertion of element 6 6 4 2 rear front 8 Enqueue element 6 4 8 2 front rear before normal array implementation 4 8 6 2 front rear after 2 4 8 front rear before circular array implementation 2 4 8 6 front rear after Queues: Circular Array Implementation
  • 25. Queues page 25 © Dr. Jonathan (Yahya) Cazalas Enqueue element 10 4 8 6 2 front rear before normal array implementation 4 8 6 10 2 front rear after 2 4 8 6 front rear before circular array implementation 2 4 8 6 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after insertion of element 10 6 4 2 rear front 8 10
  • 26. Queues page 26 © Dr. Jonathan (Yahya) Cazalas dequeue 4 8 6 10 2 front rear before normal array implementation 8 6 10 4 front rear after 2 4 8 6 10 front rear before circular array implementation 4 8 6 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation 6 4 rear front 8 10
  • 27. Queues page 27 © Dr. Jonathan (Yahya) Cazalas Enqueue element 18 8 6 10 4 front rear before normal array implementation 8 6 10 18 4 front rear after 4 8 6 10 front rear before circular array implementation 18 4 8 6 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after insertion of element 18 6 4 rear front 8 10 18
  • 28. Queues page 28 © Dr. Jonathan (Yahya) Cazalas dequeue 8 6 10 18 4 front rear before normal array implementation 6 10 18 8 front rear after 18 4 8 6 10 front rear before circular array implementation 18 8 6 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation 6 rear front 8 10 18
  • 29. Queues page 29 © Dr. Jonathan (Yahya) Cazalas dequeue 6 10 18 8 front rear before normal array implementation 10 18 6 front rear after 18 8 6 10 front rear before circular array implementation 18 6 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation 6 rear front 10 18
  • 30. Queues page 30 © Dr. Jonathan (Yahya) Cazalas dequeue 10 18 6 front rear before normal array implementation 18 10 front rear after 18 6 10 front rear before circular array implementation 18 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation rear front 10 18
  • 31. Queues page 31 © Dr. Jonathan (Yahya) Cazalas Enqueue element 9 18 10 front rear before normal array implementation 18 9 10 front rear after 18 10 front rear before circular array implementation 18 9 10 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after insertion of element 9 rear front 10 18 9
  • 32. Queues page 32 © Dr. Jonathan (Yahya) Cazalas dequeue 18 9 10 front rear before normal array implementation 9 18 front rear after 18 9 10 front rear before circular array implementation 18 9 front rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation rear front 18 9
  • 33. Queues page 33 © Dr. Jonathan (Yahya) Cazalas dequeue 9 18 front rear before normal array implementation 9 front/rear after 18 9 front rear before circular array implementation 9 front/rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation rear front 9
  • 34. Queues page 34 © Dr. Jonathan (Yahya) Cazalas dequeue – queue empties! 9 front/rear before normal array implementation front/rear after 9 front/rear before circular array implementation front/rear after Queues: Circular Array Implementation visualization of a queue implemented as a circular array after dequeue operation rear front
  • 35. Queues page 35 © Dr. Jonathan (Yahya) Cazalas  Queues:  Circular Array Implementation  So this works great in pictures  But think about something…  How did we modify the position (index) of front and rear?  Did we just increment the front/rear indices as needed?  Meaning, did we simply increment the index of rear every time an enqueue occurs?  And did we simply increment the index of front every time a dequeue occurs?  In a normal array, this is fine.  However, this is a circular array, and we must pay attention!  Simply incrementing will not cut it! Queues: Circular Array Implementation
  • 36. Queues page 36 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  How did we modify the position (index) of front and rear?  Ex: suppose we have the situation below (also from page 34)  If we dequeue, the front will need to refer to the ‘10’ in index 0!  So how do we make this happen?  Can we simply increment front?  No, we cannot, as that would be out of bounds! Queues: Circular Array Implementation 18 6 10 front rear before
  • 37. Queues page 37 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  How did we modify the position (index) of front and rear?  One possible solution: use an if/else statement  If the front is currently equal to “queue.length – 1”  Meaning, if the front is currently at the last index of the array  And if we are performing a dequeue  Then, the *new* front index will need to be set to index 0.  Else, simply increment front.  Of course, either way, we need to RETURN the value that was at the front index (because this is a dequeue operation). Queues: Circular Array Implementation 18 6 10 front rear before
  • 38. Queues page 38 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  How did we modify the position (index) of front and rear?  Here is the code: Queues: Circular Array Implementation 18 6 10 front rear before public int dequeue() { int temp = queue[front]; if (front == queue.length - 1) front = 0; // set the new front to zero else front++; // just increment the front // Finally, return the value that was at front return temp; }
  • 39. Queues page 39 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  The last solution does work…but it has a branch operation  Meaning, it has an if/else statement.  This is fine, but branching operations can be slow  Instead of using an if/else statement to recalculate the position of front, consider the following…  front = (front + 1) % queue.length;  So on our example, (6 + 1) % 7 = 0  This is PRECISELY the index we want!  The new front is calculated as index 0. Queues: Circular Array Implementation 18 6 10 front rear before The ‘7’ here refers to the size of the array
  • 40. Queues page 40 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  The last solution does work…but it has a branch operation  Meaning, it has an if/else statement.  So how do we get front to “point” to index 0?  We need to use mod (%)!  We increment front and then mod it by the queue size  front = (front + 1) % queue.length;  So now the new front refers to index 0.  This is PRECISELY the index we wanted! Queues: Circular Array Implementation 18 6 10 front rear before
  • 41. Queues page 41 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Dequeue Operation  New Solution using mod (%):  Here is the code: Queues: Circular Array Implementation 18 6 10 front rear before public int dequeue() { int temp = queue[front]; // Now update the location of front using mod front = (front+1) % queue.length; // decrement numItems (you will see why we use numItems) numItems--; // And finally, return temp...the value we dequeued return temp; }
  • 42. Queues page 42 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  We do NOT need to save the index for the rear.  Why?  Because if we know the index to the front  AND if we know the number of elements  we can quickly determine the new enqueue position  Ex: let’s say front was at index 7 and there are 2 elements  This means the rear would be at index 8  And the NEW enqueue position would be index 9  So we see that the NEW enqueue position is found by simply adding the index of the front and the number of elements  But we need to take care of wraparound… Queues: Circular Array Implementation
  • 43. Queues page 43 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Assume we have a queue of size 10  From index 0 to index 9  The front is currently index 4  And there are 6 elements already in the queue  And the next operation is enqueue(g)  Remember, enqueue is a method that we write in the program  So this ‘g’ is sent over to the enqueue method as “char val” Queues: Circular Array Implementation a b c front d f e
  • 44. Queues page 44 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Assume we have a queue of size 10  From index 0 to index 9  The front is currently index 4  And there are 6 elements already in the queue  We know that the next enqueue will go at index 0  But how do we do this?  One solution: if/else statement Queues: Circular Array Implementation a b c front d f e g
  • 45. Queues page 45 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Assume we have a queue of size 10  The front is currently index 4  numItems is currently 6 (values a to f)  IF (front+numItems) equals the size of the array  Meaning if (front+numItems == queue.length)  This means that the NEW enqueue position must be at index 0!  So we will save the new enqueue value at index 0.  Else, just save the new enqueue value at the next position available by incrementing Queues: Circular Array Implementation a b c front d f e g
  • 46. Queues page 46 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Assume we have a queue of size 10  The front is currently index 4  numItems is currently 6 (values a to f)  Here is the code: Queues: Circular Array Implementation a b c front d f e g public void enqueue(int value) { if ((front+numItems) == queue.length) queue[0] = value; else queue[(front+numItems)] = value; numItems++; // Finally, increment numItems }
  • 47. Queues page 47 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Again, the last solution does work…but it has a branch  Which is a slow operation.  Instead, we can again use mod (%).  We know that the next enqueue will go at index 0  But how do we do this in code (using mod)?  queue[(front + numItems)%queue.length] = value;  So for our example:  queue[(4 + 6) % 10] = value;  queue[0] = a … so the value ‘a’ get saved into index 0! Queues: Circular Array Implementation a b c front d f e g
  • 48. Queues page 48 © Dr. Jonathan (Yahya) Cazalas  Queues (Circular Array Implementation):  Enqueue Operation  Again, the last solution does work…but it has a branch  Which is a slow operation.  Instead, we can again use mod (%).  Here is the code: Queues: Circular Array Implementation a b c front d f e g public void enqueue(int value) { queue[(front+numItems) % queue.length] = value; numItems++; }
  • 49. Queues page 49 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: Summer in Saudi
  • 50. Queues page 50 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Implementation of Queues in JAVA:  Linked-List:  We will implement the queue as a Linked-List!  What does this mean?  This means that when you examine the code for the queue, in fact, it is simply using a Linked-List!  So then how is the Linked-List a queue? What makes it a queue?  The BEHAVIOR!  We said that an Abstract Data Type is defined based on its behaviors (the operations it can perform).  So we will restrict the behavior of the Linked-List.  We will make the Linked-List behave like (act like) a queue!
  • 51. Queues page 51 © Dr. Jonathan (Yahya) Cazalas  Implementation of Queues in JAVA:  Linked-List :  So we will restrict the behavior of the Queue.  We will make the Linked-List behave like (act like) a queue!  Example:  With a Linked-List, you can insert or delete anywhere  Insert at the beginning, middle, or end…anywhere!  However:  Since we are making this Linked-List behave like a queue:  We will ONLY allow insertion at the “back”  ENQUEUE  We will ONLY allow deletion at the “front”  DEQUEUE  So now, our Linked-List has transformed into a queue! Queues: Linked-List Implementation
  • 52. Queues page 52 © Dr. Jonathan (Yahya) Cazalas  Queues:  Linked-list implementation  Think of how this will work.  You need to know where is the front and where is the back.  So where do you want the front of the queue to be?  Do you want it to be the head of the list?  Or do you want it to be the tail/rear of the list?  The choice is yours!  Let us make the front of the queue as the head of the list.  And the rear will simply be the location of the last node. Queues: Linked-List Implementation
  • 53. Queues page 53 © Dr. Jonathan (Yahya) Cazalas  Queues:  Linked-list implementation  Dequeue:  Remember, the front of the queue is the head of the list.  Therefore, when we dequeue, this means we will simply perform a delete command from the FRONT of the linked list.  This is very easy to do…we simply make front point to front.next!  front = front.getNext();  There are a few other things to consider as well  See the QueueLL.java code given on the website. Queues: Linked-List Implementation
  • 54. Queues page 54 © Dr. Jonathan (Yahya) Cazalas  Queues:  Linked-list implementation  Enqueue:  Now consider enqueue. How will you enqueue the next item into the queue?  Well, you need to know where is the current last item.  One solution…traverse each time to the current last item.  And then enqueue the new item afterwards.  This would be very slow!  Every time you want to enqueue, you would have to traverse your entire list.  What if the list was huuuuuuuge? Queues: Linked-List Implementation
  • 55. Queues page 55 © Dr. Jonathan (Yahya) Cazalas  Queues:  Linked-list implementation  Enqueue:  Better solution: used a tail/back pointer  Meaning inside the QueueLL.java code, you will always maintain (keep) a reference to the last node  So this class will have two important variables:  private QueueNode front;  private QueueNode back;  Both of these variables need to be updated whenever enqueue and dequeue operations are performed  See code on website for more details. Queues: Linked-List Implementation
  • 56. Queues page 56 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues:  Therefore:  An enqueue is simply inserting into the back of the linked list!  This is very easy because we keep a pointer to the last node.  It only requires changing two references!  A dequeue would be deleting the front node  Again, the easiest type of deletion  Only requiring changing two references!  So, in fact, a linked-list version of a queue is EASIER to code than a regular linked list!
  • 57. Queues page 57 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues:  So each node will be an element of the queue  Each node has a data value  Each node also has a next  We simply enqueue (insert at back)  And dequeue (delete the front node)
  • 58. Queues page 58 © Dr. Jonathan (Yahya) Cazalas  Linked Lists Implementation of Queues:  So we will create two classes (like Linked-Lists)  QueueNode.java (this is like the LLnode class)  QueueLL.java (this is like the LinkedList class)  We use most of the SAME methods as used for the Linked List class  However, we RESTRICT the functionality  Now, we cannot insert anywhere in the list  We can only insert at the back (enqueue)  Now, we cannot delete from anywhere in the list  We can only delete from the front (dequeue) Queues: Linked-List Implementation
  • 59. Queues page 59 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues:  Code for QueueNode.java public class QueueNode { private int data; private QueueNode next; // CONSTRUCTORS public QueueNode() { data = 0; next = null; } public QueueNode(int data) { this.data = data; next = null; } public QueueNode(int data, QueueNode next) { this.data = data; this.next = next; }
  • 60. Queues page 60 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues: ... // ACCESSORS public int getData() { return data; } public QueueNode getNext() { return next; } // MUTATORS public void setData(int data) { this.data = data; } public void setNext(QueueNode next) { this.next = next; } }
  • 61. Queues page 61 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues:  Code for QueueLL.java (similar to LinkedList.java) public class QueueLL { // top: reference variable to the top of the stack // (same as "head" of linked list) private QueueNode front; private QueueNode back; // CONSTRUCTOR public QueueLL() { front = null; back = null; } // MANY methods go here to control the stack // POP, PUSH, TOP and more...
  • 62. Queues page 62 © Dr. Jonathan (Yahya) Cazalas Queues: Linked-List Implementation  Linked Lists Implementation of Queues:  Code for QueueLL.java (similar to LinkedList.java)  dequeue() method: // QueueNode | dequeue() public QueueNode dequeue() { QueueNode temp = front; front = dequeue(front); if (front == null) back = null; return temp; } // QueueNode | dequeue(QueueNode) private QueueNode dequeue(QueueNode front) { front = front.getNext(); return front; }
  • 63. Queues page 63 © Dr. Jonathan (Yahya) Cazalas Queues WASN’T THAT SUPERB!
  • 64. Queues page 64 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 65. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Queues