CC104 - Lessons 5
CC104 - Lessons 5
and
Engr.Algorithms
Prepared By
Regine Jesa J. Palara,
MIT
Learning
Objectives
At the end of the topic session,
the students should be able to:
Use queue operations in a program;
Differentiatethe built-in Java and
Python methods; and
Develop a simple program that makes
use of queues.
FUNDAMENTALS
A queue is an ordered list in which the first
element added is the first element
retrieved or removed (First-In, First-Out).
Thefirst element in the queue is known as
the head of the queue.
Example: A queue of customers: Lisa,
Jennie, Jisoo, Rose Lisa
Jennie
Jisoo
Rose
FUNDAMENTALS
Lisa is the customer who has been waiting the
longest, while Rose is the one who
last arrived. Lisa will be the first
removed from the queue.
customer
Queues are used in any of the following:
CPU and disk scheduling
Serving requests on a single shared
resource, such as a printer
Managing customers trying to get hold
of a hotline.
FUNDAMENTALS
The methods of the Queue interface from
the java.util package are used to
implement queues in Java. Since interfaces
cannot be instantiated, LinkedList is used
to instantiate a Queue object.
The methods of collections.deque are used
to implement queues in Python. The import
statement shall be from collections import
deque.
FUNDAMENTALS
The list methods can also be used to
implement queues in Python.
The two (2) main queue operations are
the following:
Enqueue – adds an item into the queue.
Method in Java: offer()
Queue queue = new LinkedList(); queue.offer("Lisa");
Method in Python: append()
queue = deque([])
queue.append("Jennie")
FUNDAMENTALS
Dequeue – removes the head of the queue
Method in Java: poll()
Method in Python: popleft()
Other queue operations:
Peek – retrieves the head of the queue
Method in Java: peek()
Syntax in Python: queue_name[0]
FUNDAMENTALS
Test whether queue is empty
For Java, use the isEmpty() method.
For Python, use the if not condition, followed by
the queue name and a colon.
Example:
queue = deque([])
if not queue:
print("Queue
is empty.")
FUNDAMENTALS
Other Queue Methods
Javamethods offer(), poll(), and peek() do not
throw exceptions. The methods add(), remove(),
and element() perform the same tasks but throw
exceptions.
Other methods that can be used for both queues
and lists are the following:
FUNDAMENTALS