0% found this document useful (0 votes)
20 views

Lecture - Queues Data Structures & Operations

Uploaded by

thegeotheo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lecture - Queues Data Structures & Operations

Uploaded by

thegeotheo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Queues data structures & enqueue

and dequeue operations


Lecture: Rufus Gikera

1
Introduction to Queues
• A queue is a linear data structure that follows
the First-In-First-Out (FIFO) principle.
• This means that the first element added to the
queue will be the first one to be removed.
Characteristics:
• FIFO Principle: The first element added is the
first one removed.
• Linear Structure: Elements are stored in a
sequential manner.
2
Queue
• Queue is a list with the restriction that insertions are done at
one end and deletions are done at the other
– First-In, First-Out ("FIFO”)
– Elements are stored in order of
insertion but don't have indexes.
– Client can only add to the end of the
queue, and can only examine/remove
the front of the queue.

3
Basic queue operations

– add (enqueue): Add an element to the back.


– remove (dequeue): Remove the front
element.
– peek: Examine the element at the front.

4
Cont.. Basic Operations

• Enqueue: The process of adding an element to the


end of the queue.
– Operation:
• Check if the queue is full.
• If not, add the element to the end of the queue.
• Update the rear pointer to the new end of the queue.
• Dequeue: The process of removing an element from
the front of the queue.
– Operation:
• Check if the queue is empty.
• If not, remove the element from the front of the queue.
• Update the front pointer to the next element in the queue.
5
Enqueue (ItemType newItem)
• Function: Adds newItem to the rear of the
queue.
• Preconditions: Queue has been initialized
and is not full.
• Postconditions: newItem is at rear of
queue.
Dequeue (ItemType& item)
• Function: Removes front item from queue and
returns it in item.
• Preconditions: Queue has been initialized and
is not empty.
• Postconditions: Front element has been
removed from queue and item is a copy of
removed element.
Queue Representation
• Front: Points to the first element in the queue.
• Rear: Points to the last element in the queue.

8
Queues in computer science
• Operating systems:
– queue of print jobs to send to the printer
– queue of programs / processes to be run
– queue of network data packets to send

• Programming:
– modeling a line of customers or clients
– storing a queue of computations to be performed in order

• Real world examples:


– people on an escalator or waiting in a line
– cars at a gas station (or on an assembly line)
9
Enqueue Operation
• Check for Overflow:
– If the queue is full (i.e., no more space to add
elements), report an overflow condition.
• Insert Element:
– Place the new element at the position indicated by
the rear pointer.
• Update Rear Pointer:
– Increment the rear pointer to the next position.

10
Using Queues
add(value places given value at back of queue
)
remove() removes value from front of queue and returns it;
throws a NoSuchElementException if queue is empty
peek() returns front value from queue without removing it;
returns null if queue is empty
size() returns number of elements in queue
isEmpty() returns true if queue has no elements
Queue<Integer> q = new LinkedList<Integer>();
q.add(42);
q.add(-3);
q.add(17); // front [42, -3, 17] back
System.out.println(q.remove()); // 42

– IMPORTANT: When constructing a queue you must use a new


LinkedList object instead of a new Queue object.

11
Algorithm for Enqueue
Procedure Enqueue(queue, element)
if queue is full
print "Queue Overflow"
else
rear = rear + 1
queue[rear] = element
end if
End Procedure

12
Dequeue Operation
• Check for Underflow:
– If the queue is empty (i.e., no elements to
remove), report an underflow condition.
• Remove Element:
– Retrieve the element from the position indicated
by the front pointer.
• Update Front Pointer:
– Increment the front pointer to the next position.

13
Algorithm for Dequeue:
Procedure Dequeue(queue)
if queue is empty
print "Queue Underflow"
else
element = queue[front]
front = front + 1
return element
end if
End Procedure
14
Implementing Queue ADT: Array Queue
• Keep track of the number of elements in the
queue, size.
• Enqueue at the back of the array (size).
• Dequeue at the front of the array (index 0).

– what is bad about this implementation?


– what if we enqueue at 0 and dequeue at size?

15
Implementing Queue ADT:
Circular Array Queue
• Neat trick: use a circular array 7 0

to insert and remove items 6 1


from a queue in constant time.
• The idea of a circular array is 5 2

that the end of the array 4 3

“wraps around” to the start of


the array.
Q: 0 size - 1
b c d e f
front back
16
Linked List Queue
b c d e f

front back

// Basic idea only!


enqueue(x) {
back.next = new Node(x);
back = back.next;
}
// Basic idea only!
dequeue() {
x = front.item;
front = front.next;
return x;
}
17
Queue: Circular Array vs. Linked List
• Circular Array • Linked List
– May waste unneeded – Always just enough
space or run out of space
space – But more space per
– Space per element element
excellent – Operations very simple /
– Operations very simple / fast
fast

18
Exercise: Linked List Queue Implementation

• Implement a queue class that stores String


values using a singly linked list with both
nodes to indicate the front and the back of the
queue as below. The queue should implement
the interface on the next slide.
b c d e f

front back

19
Implementing Queues in Python
class Queue: self.rear += 1
def __init__(self, max_size): print(f"Enqueued: {item}")
self.queue = []
self.max_size = max_size def dequeue(self):
self.front = 0 if self.is_empty():
self.rear = -1 print("Queue Underflow")
else:
def is_full(self): item = self.queue[self.front]
return len(self.queue) == self.max_size self.queue = self.queue[1:]
self.rear -= 1
def is_empty(self): print(f"Dequeued: {item}")
return len(self.queue) == 0 return item

def enqueue(self, item):


if self.is_full():
print("Queue Overflow")
else:
self.queue.append(item)
20
Implementing Queues in Python
Example usage
queue = Queue(5)
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.dequeue()
queue.enqueue(40)

21
Example
Queue: [10, 20, 30], Front = 0
Dequeue:
Check if queue is empty: No.
Remove element at position 0: 10.
Update front pointer: Front = 1.
Queue: [20, 30]

22
Visualization
Before Dequeue: After Dequeue:
Front → [10] [20] [30] Front → [20] [30]
^front = 0 ^front = 1

23
Types of Queues

• Simple Queue:
– Also known as a linear queue.
– Follows the basic FIFO principle.
• Circular Queue:
– Overcomes the limitations of the simple queue by
connecting the rear end back to the front, forming
a circle.
– Useful for fixed-size buffer management.

24
Types of Queues
• Priority Queue:
– Elements are processed based on priority rather
than the order they arrive.
– Higher priority elements are dequeued before
lower priority ones.
• Double-Ended Queue (Deque):
– Allows insertion and deletion from both ends
(front and rear).
– Can be used to implement both stacks and queues.

25
Applications of Queues

• Scheduling:
– CPU scheduling and disk scheduling.
– Task scheduling in operating systems.
• Buffer Management:
– Managing data packets in network communications.
– Printer job management.
• Breadth-First Search (BFS):
– A graph traversal algorithm that uses queues.
• Simulation and Modeling:
– Managing customers in a service system (e.g., ticket
queues, call centers).
26
Summary
• Queues follow the FIFO principle.
• Enqueue adds elements to the rear.
• Dequeue removes elements from the front.
• Essential for various applications in computing
and real-world scenarios.

27
Case Study: Simulation

• Queuing System: consists of servers and


queues of objects to be served.

• Simulation: a program that determines


how long items must wait in line before
being served.
Case Study: Simulation (cont.)
• Inputs to the simulation:
(1) the length of the simulation
(2) the average transaction time
(3) the number of servers
(4) the average time between job
arrivals
Case Study: Simulation (cont.)
• Parameters the simulation must vary:
(1) number of servers
(2) time between arrivals of items

• Output of simulation: average wait time.


One-dimensional arrays and multi-
dimensional arrays
An array is a data structure that stores a collection
of elements, typically of the same type, in a
contiguous memory location. Arrays are used to
store multiple values in a single variable.

Types of Arrays:
• One-Dimensional Arrays
• Multi-Dimensional Arrays (including two-
dimensional and higher-dimensional arrays)
31
One-Dimensional Arrays

• Definition: A one-dimensional array (1D array)


is a list of elements, all of the same type,
stored in contiguous memory locations. It can
be thought of as a row of elements.

Declaration:
• Syntax (C/C++): type arrayName[size];
• Example: int numbers[5];
• At Declaration: int numbers[5] = {1, 2, 3, 4, 5};
32
Accessing Elements
• Syntax: arrayName[index];
• Example: int firstNumber = numbers[0];

33
Example in C++
#include <iostream>
using namespace std;

int main() {
int numbers[5] = {1, 2, 3, 4, 5};

cout << "Elements of the array: ";


for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}

return 0;
}
34
Multi-Dimensional Arrays

• A multi-dimensional array is an array of arrays. The


most common type is the two-dimensional array, but
arrays can have more dimensions.

Two-Dimensional Arrays (2D Arrays):


A 2D array can be thought of as a table of elements,
with rows and columns.
• Declaration (C/C++): type arrayName[rows]
[columns];
• Example: int matrix[3][4];
35
Multidimensional Arrays
• A multidimensional array is actually an array in which each
element is another array.
• A three- dimensional array consists of an array of two-
dimensional arrays.
• A two-dimensional array consists of an array of one-
dimensional arrays.
• For example, suppose x = new int[2] [2][5].
– x[0] and x[1] are two-dimensional arrays.
– x[0][0], x[0][1], x[1][0], and x[1][1] are one-dimensional arrays and
each contains five elements.
– x.length is 2,
– x[0].length and x[1].length are 2, and
– X[0][0].length, x[0][1].length, x[1][0].length, and x[1][1].length are 5.

36
Example

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

37
Accessing Elements

Syntax: arrayName[rowIndex][columnIndex];
Example: int firstElement = matrix[0][0];

38
Example in C++
#include <iostream> for (int i = 0; i < 3; i++) {
using namespace std; for (int j = 0; j < 4; j++) {
cout << matrix[i][j] <<
int main() { " ";
int matrix[3][4] = { }
{1, 2, 3, 4}, cout << endl;
{5, 6, 7, 8}, }
{9, 10, 11, 12}
}; return 0;
}
cout << "Elements of the
2D array: " << endl;
39
Higher-Dimensional Arrays
• Three-Dimensional Arrays: Can be thought of
as a cube of elements.
• Declaration (C/C++): type arrayName[size1]
[size2][size3];
• Example: int threeD[2][3][4];

40
Applications of Arrays

• One-Dimensional Arrays:
– Storing a list of items like numbers, names, etc.
– Implementing other data structures like stacks and
queues.
• Two-Dimensional Arrays:
– Representing matrices in mathematics.
– Storing tabular data, such as a spreadsheet or grid.
– Game boards, like chess or tic-tac-toe.

41
Summary

• One-Dimensional Arrays: Linear list of


elements.
• Two-Dimensional Arrays: Array of arrays,
representing a table of elements.
• Arrays are fundamental data structures used
to store collections of data efficiently.

42

You might also like