SlideShare a Scribd company logo
Data Structures & Algorithms
1
Lecturer: Dr. Muhammad M Iqbal
Ph.D (DCU), M.Phil (GCU)
Stacks and Queues
2
Stack
● An entry added or pushes on
to the top of a stack.
● An entry is removed, or
popped from the top of stack.
3
Stacks
• A stack is a classic collection used to help to solve
many types of problems
• A stack is a linear collection whose elements are added
in a last in, first out (LIFO) manner
• This means that the last element to be put on a stack is
the first one to be removed
• Think of a stack of books,
where you add and remove from
the top, but can't reach into the
middle 4
Stack Operations
• Some collections use particular terms for their
operations
• These are the classic stack operations:
5
Example of Stack
● Surfing the Web on a browser:
– The sequence of back clicks loads the
browser with Web pages in reverse order of
visit.
– The last visited page is the first loaded when
going back.
● A stack is a collection of entries that
demonstrates exactly this last in, first out
behavior, called LIFO in short. 6
Applications of Stacks
• Direct applications
– Undo sequence in a text editor
– Chain of method calls in the Java Virtual
Machine
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
7
The Stack ADT
• The Stack ADT stores arbitrary
objects
• Insertions and deletions follow the
last-in first-out scheme
• Think of a spring-loaded plate
dispenser
• Main stack operations:
– push(object): inserts an element
– object pop(): removes and returns the
last inserted element
• Auxiliary stack operations:
– object top(): returns the last
inserted element without
removing it
– integer size(): returns the
number of elements stored
– boolean isEmpty(): indicates
whether no elements are
stored
8
Stack Interface in Java
• Java interface
corresponding to our Stack
ADT
• Assumes null is returned
from top() and pop() when
stack is empty
• Different from the built-in
Java class java.util.Stack
public interface Stack<E> {
int size();
boolean isEmpty();
E top();
void push(E element);
E pop();
}
9
Array-based Stack
• A simple way of
implementing the Stack
ADT uses an array
• We add elements from left
to right
• A variable keeps track of
the index of the top element
S
0 1 2 t
…
Algorithm size()
return t + 1
Algorithm pop()
if isEmpty() then
return null
else
t  t  1
return S[t + 1]
10
Array-based Stack (cont.)
• The array storing the stack
elements may become full
• A push operation will then
throw a FullStackException
– Limitation of the array-based
implementation
– Not intrinsic to the Stack ADT
S
0 1 2 t
…
Algorithm push(o)
if t = S.length  1 then
throw IllegalStateException
else
t  t + 1
S[t]  o
11
Example
http://www.cs.armstrong.edu/liang/animation/animation.html
ArrayStack.java
12
Stack
Initialization
13
Stack
Push
Check if stack is full
If not
• increment top
• add data to stack
14
Stack
Push with FullStackException
15
Stack
Sample FullStackException
• It is used inside a sub-class method definition to call a method defined
in the super class.
• Private methods of the super-class cannot be called.
• Only public and protected methods can be called by the super
keyword. 16
Stack
Pop
Check if the stack is empty
If not
• Return data
• Decrement top of the stack
17
Stack
Pop with EmptyStackException
18
Stack
Peek
Check if stack is empty
If not
• Return data
• Leave top alone
19
Stack
Peek with EmptyStackException
20
Stack
Limited Size
• It is not very useful to have a data structure limited by the
array size.
• Java themselves implemented the Stack class with an array but
they allowed for it to extend.
• To do this, we need to have a defined point where we create a
new, bigger array and copy across.
• When we hit the full mark, rather than throw exceptions, let's
do something more useful.
• We create a new array of a bigger size.
• How do we decide how much bigger to make it? 21
Stack
Resizing
• We can increase the size by a fixed amount
• Or we can increase the size by a percentage of the previous
amount
• Fixed amount is good for situations where we have a steadily
increasing stream of data to store/use
• Factor-based increases are good for systems that are increasing
at a much higher rate or if we vastly underestimated the size to
begin with
• This is only relevant for the push() operation
22
Stack
Resize on Push
• Check if full
• If full
• resize array and copy contents across
• add data ([++top])
• If not full
• add data ([++top])
23
Stack
Resize on Push (Fixed Amount)
24
Stack
Resizing
• We should also keep track of whether we have way too much
space reserved but aren't using it
• e.g., if the system receives irregular spikes in traffic, there is
no need for a giant array to hold a handful of data
• You can check at any point but it makes most sense to check
on a pop
• If the stack is only about half full, maybe consider making it
smaller (again, depends on your system)
25
Stack
Resize on Pop
• Check if empty ! throw exception
• If not
• check if too long
• if yes
– resize
– pop
• if no
– pop 26
Stack
Resize on Pop
27
Stack
Lets use our Stacks
Reverse a set of numbers
ReverseWithStack.java 28
Stack
ArrayStack as a generic type
ArrayStack.java 29
Queues
30
The Queue ADT
• The Queue ADT stores arbitrary
objects
• Insertions and deletions follow the
first-in first-out scheme
• Insertions are at the rear of the
queue and removals are at the
front of the queue
• Main queue operations:
– enqueue(object): inserts an element at
the end of the queue
– object dequeue(): removes and
returns the element at the front of the
queue
• Auxiliary queue operations:
– object first(): returns the
element at the front without
removing it
– integer size(): returns the
number of elements stored
– boolean isEmpty(): indicates
whether no elements are
stored
• Boundary cases:
– Attempting the execution of
dequeue or first on an empty
queue returns null
31
Queue Properties and Attributes
Properties
1.Queues are FIFO data structures. All insertions are done at the rear and all deletions
at the front
2.The front always refers to the first element in the queue
3.The rear always refers to the position where the next element is to be inserted in the
queue
4.The queue has a fixed upper bound (capacity) on the number of elements it can store
Attributes
capacity : The maximum number of elements that can be in the queue at one time.
size : The number of elements in the queue: 0 ≤ size ≤ capacity at all times
front : The first element of the queue or a null value not part of the queue when the
queue is empty
rear : The position in the queue where the next element is to be inserted or a null
value not part of the queue if the queue is full 32
Example
Operation Output Q
enqueue(5) – (5)
enqueue(3) – (5, 3)
dequeue() 5 (3)
enqueue(7) – (3, 7)
dequeue() 3 (7)
first() 7 (7)
dequeue() 7 ()
dequeue() null ()
isEmpty() true ()
enqueue(9) – (9)
enqueue(7) – (9, 7)
size() 2 (9, 7)
enqueue(3) – (9, 7, 3)
enqueue(5) – (9, 7, 3, 5)
dequeue() 9 (7, 3, 5)
http://www.cs.armstrong.edu/liang/animation/web/Queue.html 33
Applications of Queues
• Direct applications
– Waiting lists, bureaucracy
– Access to shared resources (e.g., printer)
– Multiprogramming
• Indirect applications
– Auxiliary data structure for algorithms
– Component of other data structures
34
ArrayQueue: Using an Array
underlying data structure
(a) Queue.front is always at 0 – shift elements left on dequeue().
A Queue is a linear structure that is accessed at both ends.
How do we map front and rear to the two ends of an array?
(b) Queue.rear is always at 0 – shift elements right on enqueue().35
ArrayQueue: Using an Array
underlying data structure
• Neither of these solutions is satisfactory as they
both involve moving data elements, which is
expensive
Idea: Instead of moving data elements to a fixed position
for front, let front advance through the array.
Hmmm….what do we do when front catches up with rear? 36
Array-based Queue
• Let’s assume that as elements are inserted into a queue,
we store them in an array such that the first element is at
index 0, the second element at index 1, and so on.
• Using an array to store elements of a queue, such that the
first element inserted, “A”, is at cell 0, the second
element inserted, “B”, at cell 1, and so on.
37
How to Implement a dequeue
operation
• The element to be removed is stored at index 0 of the array.
• One strategy is to execute a loop to shift all other elements of the
queue one cell to the left, so that the front of the queue is again
aligned with cell 0 of the array.
• Unfortunately, the use of such a loop would result in an O(n) running
time for the dequeue method.
• Allowing the front of the queue to drift away from index 0. In this
representation, index f denotes the location of the front of the queue.38
How to Avoid Loop
• We will replace a dequeued element in the array with a null reference,
and maintain an explicit variable f to represent the index of the element
that is currently at the front of the queue.
• Such an algorithm for dequeue would run in O(1) time.
• After several dequeue operations, this approach might lead to the
configuration portrayed in Figure.
• However, there remains a challenge with the revised approach. With
an array of capacity N, we should be able to store up to N elements
before reaching any exceptional case. 39
Using an Array Circularly
• In developing a robust queue implementation, we allow both the front
and back of the queue to drift rightward, with the contents of the queue
“wrapping around” the end of an array, as necessary.
• Assuming that the array has fixed length N, new elements are enqueued
toward the “end” of the current queue, progressing from the front to
index N −1 and continuing at index 0, then 1.
• Figure illustrates such a queue with first element F and last element R.
40
Circular Queue
• Use an array of size N in a circular fashion
• Two variables keep track of the front and size
f index of the front element
sz number of stored elements
• When the queue has fewer than N elements, array location
r = (f + sz) mod N is the first empty slot past the rear of
the queue
Q
0 1 2 rf
normal configuration
Q
0 1 2 fr
wrapped-around configuration
41
Example
42
(green)
Queue Operations
• We use the modulo
operator
(remainder of
division)
Algorithm size()
return sz
Algorithm isEmpty()
return (sz == 0)
Q
0 1 2 rf
Q
0 1 2 fr
43
Queue Operations (cont.)
Algorithm enqueue(o)
if size() = N  1 then
throw IllegalStateException
else
r  (f + sz) mod N
Q[r]  o
sz  (sz + 1)
• Operation enqueue
throws an exception if the
array is full
• This exception is
implementation-
dependent
Q
0 1 2 rf
Q
0 1 2 fr
44
Queue Operations (cont.)
• Note that operation
dequeue returns null if
the queue is empty
Algorithm dequeue()
if isEmpty() then
return null
else
o  Q[f]
f  (f + 1) mod N
sz  (sz  1)
return o
Q
0 1 2 rf
Q
0 1 2 fr 45
Queue Interface in Java
• Java interface
corresponding to our
Queue ADT
• Assumes that first()
and dequeue() return
null if queue is
empty
public interface Queue<E> {
int size();
boolean isEmpty();
E first();
void enqueue(E e);
E dequeue();
}
46
Array-based Implementation
47
Array-based Implementation (2)
48
Comparison to java.util.Queue
• Our Queue methods and corresponding
methods of java.util.Queue:
49
Application: Round Robin Schedulers
• We can implement a round robin scheduler using a queue
Q by repeatedly performing the following steps:
1. e = Q.dequeue()
2. Service element e
3. Q.enqueue(e)
Shared
Service
Queue
EnqueueDequeue
50
Resources/ References
• Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson,
Ronald L. Rivest and Clifford Stein 3rd, 2009, MIT Press and
McGraw-Hill.
• Data Structures: Abstraction and Design Using Java, Elliott B.
Koffmann, 2nd, 2010, Wiley.
• Data Structures and algorithm analysis in java, Mark A. Weiss, 3rd,
2011, Prentice Hall.
• Frank M. Carrano, Data Structures and Abstractions with Java™, 3rd
Edition, Prentice Hall, PEARSON, ISBN-10: 0-13-610091-0.
• This lecture used some images and videos from the Google search
repository to raise the understanding level of students.
https://www.google.ie/search?
Dr. Muhammad M Iqbal*
51

More Related Content

PPTX
Analysis of algorithms
PPTX
Presentation on Elementary data structures
PPTX
Unit II - LINEAR DATA STRUCTURES
PPTX
stack & queue
PPT
Chapter 6 ds
PDF
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
PPTX
Data structures and algorithms
PDF
Algorithms Lecture 6: Searching Algorithms
Analysis of algorithms
Presentation on Elementary data structures
Unit II - LINEAR DATA STRUCTURES
stack & queue
Chapter 6 ds
UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES
Data structures and algorithms
Algorithms Lecture 6: Searching Algorithms

What's hot (20)

PPTX
Queue ppt
PDF
stacks and queues
PPT
Queue Data Structure
DOCX
Best,worst,average case .17581556 045
PPT
Chapter 11 ds
PPTX
Queue Data Structure
PPT
Chapter 4 ds
PPTX
Data structures and algorithms
PPTX
Big o notation
PPTX
Stack and Queue
PPTX
PPT
Sorting Seminar Presentation by Ashin Guha Majumder
PPTX
Data structure using c module 1
PPTX
Stack data structure in Data Structure using C
PPTX
Data structures
PPTX
Searching Algorithms
PPT
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
PPT
2 a stacks
PPSX
Data structure stack&queue basics
Queue ppt
stacks and queues
Queue Data Structure
Best,worst,average case .17581556 045
Chapter 11 ds
Queue Data Structure
Chapter 4 ds
Data structures and algorithms
Big o notation
Stack and Queue
Sorting Seminar Presentation by Ashin Guha Majumder
Data structure using c module 1
Stack data structure in Data Structure using C
Data structures
Searching Algorithms
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
2 a stacks
Data structure stack&queue basics
Ad

Similar to stacks and queues for public (20)

PPTX
STACK.pptx
PPTX
queue.pptx
PPTX
stack_presentaton_HUSNAIN[2].pojklklklptx
PPTX
My lecture stack_queue_operation
PPTX
Queues
PPT
Queues in C++ detailed explanation and examples .ppt
PPTX
STACKS AND QUEUES.pptx
PPTX
STACKS AND QUEUES.pptx
PPTX
PPTX
Stack in Sata Structure
PDF
Queue ADT for data structure for computer
PPTX
QUEUE in data-structure (classification, working procedure, Applications)
PPT
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
PPTX
Lecture 2 Introduction to Stacks and Queues.pptx
PPT
Data structures
PPTX
The presention is about the queue data structure
PPT
Data Structures
PPTX
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
STACK.pptx
queue.pptx
stack_presentaton_HUSNAIN[2].pojklklklptx
My lecture stack_queue_operation
Queues
Queues in C++ detailed explanation and examples .ppt
STACKS AND QUEUES.pptx
STACKS AND QUEUES.pptx
Stack in Sata Structure
Queue ADT for data structure for computer
QUEUE in data-structure (classification, working procedure, Applications)
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
Lecture 2 Introduction to Stacks and Queues.pptx
Data structures
The presention is about the queue data structure
Data Structures
DATA STRUCTURE AND COMPUTER ALGORITHMS LECTURE 2
Ad

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
master seminar digital applications in india
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Trump Administration's workforce development strategy
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Computing-Curriculum for Schools in Ghana
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
master seminar digital applications in india
Final Presentation General Medicine 03-08-2024.pptx
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Final Presentation General Medicine 03-08-2024.pptx
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Anesthesia in Laparoscopic Surgery in India
A systematic review of self-coping strategies used by university students to ...
Trump Administration's workforce development strategy
Updated Idioms and Phrasal Verbs in English subject
Yogi Goddess Pres Conference Studio Updates
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial diseases, their pathogenesis and prophylaxis
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Cell Structure & Organelles in detailed.
What if we spent less time fighting change, and more time building what’s rig...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf

stacks and queues for public

  • 1. Data Structures & Algorithms 1 Lecturer: Dr. Muhammad M Iqbal Ph.D (DCU), M.Phil (GCU)
  • 3. Stack ● An entry added or pushes on to the top of a stack. ● An entry is removed, or popped from the top of stack. 3
  • 4. Stacks • A stack is a classic collection used to help to solve many types of problems • A stack is a linear collection whose elements are added in a last in, first out (LIFO) manner • This means that the last element to be put on a stack is the first one to be removed • Think of a stack of books, where you add and remove from the top, but can't reach into the middle 4
  • 5. Stack Operations • Some collections use particular terms for their operations • These are the classic stack operations: 5
  • 6. Example of Stack ● Surfing the Web on a browser: – The sequence of back clicks loads the browser with Web pages in reverse order of visit. – The last visited page is the first loaded when going back. ● A stack is a collection of entries that demonstrates exactly this last in, first out behavior, called LIFO in short. 6
  • 7. Applications of Stacks • Direct applications – Undo sequence in a text editor – Chain of method calls in the Java Virtual Machine • Indirect applications – Auxiliary data structure for algorithms – Component of other data structures 7
  • 8. The Stack ADT • The Stack ADT stores arbitrary objects • Insertions and deletions follow the last-in first-out scheme • Think of a spring-loaded plate dispenser • Main stack operations: – push(object): inserts an element – object pop(): removes and returns the last inserted element • Auxiliary stack operations: – object top(): returns the last inserted element without removing it – integer size(): returns the number of elements stored – boolean isEmpty(): indicates whether no elements are stored 8
  • 9. Stack Interface in Java • Java interface corresponding to our Stack ADT • Assumes null is returned from top() and pop() when stack is empty • Different from the built-in Java class java.util.Stack public interface Stack<E> { int size(); boolean isEmpty(); E top(); void push(E element); E pop(); } 9
  • 10. Array-based Stack • A simple way of implementing the Stack ADT uses an array • We add elements from left to right • A variable keeps track of the index of the top element S 0 1 2 t … Algorithm size() return t + 1 Algorithm pop() if isEmpty() then return null else t  t  1 return S[t + 1] 10
  • 11. Array-based Stack (cont.) • The array storing the stack elements may become full • A push operation will then throw a FullStackException – Limitation of the array-based implementation – Not intrinsic to the Stack ADT S 0 1 2 t … Algorithm push(o) if t = S.length  1 then throw IllegalStateException else t  t + 1 S[t]  o 11
  • 14. Stack Push Check if stack is full If not • increment top • add data to stack 14
  • 16. Stack Sample FullStackException • It is used inside a sub-class method definition to call a method defined in the super class. • Private methods of the super-class cannot be called. • Only public and protected methods can be called by the super keyword. 16
  • 17. Stack Pop Check if the stack is empty If not • Return data • Decrement top of the stack 17
  • 19. Stack Peek Check if stack is empty If not • Return data • Leave top alone 19
  • 21. Stack Limited Size • It is not very useful to have a data structure limited by the array size. • Java themselves implemented the Stack class with an array but they allowed for it to extend. • To do this, we need to have a defined point where we create a new, bigger array and copy across. • When we hit the full mark, rather than throw exceptions, let's do something more useful. • We create a new array of a bigger size. • How do we decide how much bigger to make it? 21
  • 22. Stack Resizing • We can increase the size by a fixed amount • Or we can increase the size by a percentage of the previous amount • Fixed amount is good for situations where we have a steadily increasing stream of data to store/use • Factor-based increases are good for systems that are increasing at a much higher rate or if we vastly underestimated the size to begin with • This is only relevant for the push() operation 22
  • 23. Stack Resize on Push • Check if full • If full • resize array and copy contents across • add data ([++top]) • If not full • add data ([++top]) 23
  • 24. Stack Resize on Push (Fixed Amount) 24
  • 25. Stack Resizing • We should also keep track of whether we have way too much space reserved but aren't using it • e.g., if the system receives irregular spikes in traffic, there is no need for a giant array to hold a handful of data • You can check at any point but it makes most sense to check on a pop • If the stack is only about half full, maybe consider making it smaller (again, depends on your system) 25
  • 26. Stack Resize on Pop • Check if empty ! throw exception • If not • check if too long • if yes – resize – pop • if no – pop 26
  • 28. Stack Lets use our Stacks Reverse a set of numbers ReverseWithStack.java 28
  • 29. Stack ArrayStack as a generic type ArrayStack.java 29
  • 31. The Queue ADT • The Queue ADT stores arbitrary objects • Insertions and deletions follow the first-in first-out scheme • Insertions are at the rear of the queue and removals are at the front of the queue • Main queue operations: – enqueue(object): inserts an element at the end of the queue – object dequeue(): removes and returns the element at the front of the queue • Auxiliary queue operations: – object first(): returns the element at the front without removing it – integer size(): returns the number of elements stored – boolean isEmpty(): indicates whether no elements are stored • Boundary cases: – Attempting the execution of dequeue or first on an empty queue returns null 31
  • 32. Queue Properties and Attributes Properties 1.Queues are FIFO data structures. All insertions are done at the rear and all deletions at the front 2.The front always refers to the first element in the queue 3.The rear always refers to the position where the next element is to be inserted in the queue 4.The queue has a fixed upper bound (capacity) on the number of elements it can store Attributes capacity : The maximum number of elements that can be in the queue at one time. size : The number of elements in the queue: 0 ≤ size ≤ capacity at all times front : The first element of the queue or a null value not part of the queue when the queue is empty rear : The position in the queue where the next element is to be inserted or a null value not part of the queue if the queue is full 32
  • 33. Example Operation Output Q enqueue(5) – (5) enqueue(3) – (5, 3) dequeue() 5 (3) enqueue(7) – (3, 7) dequeue() 3 (7) first() 7 (7) dequeue() 7 () dequeue() null () isEmpty() true () enqueue(9) – (9) enqueue(7) – (9, 7) size() 2 (9, 7) enqueue(3) – (9, 7, 3) enqueue(5) – (9, 7, 3, 5) dequeue() 9 (7, 3, 5) http://www.cs.armstrong.edu/liang/animation/web/Queue.html 33
  • 34. Applications of Queues • Direct applications – Waiting lists, bureaucracy – Access to shared resources (e.g., printer) – Multiprogramming • Indirect applications – Auxiliary data structure for algorithms – Component of other data structures 34
  • 35. ArrayQueue: Using an Array underlying data structure (a) Queue.front is always at 0 – shift elements left on dequeue(). A Queue is a linear structure that is accessed at both ends. How do we map front and rear to the two ends of an array? (b) Queue.rear is always at 0 – shift elements right on enqueue().35
  • 36. ArrayQueue: Using an Array underlying data structure • Neither of these solutions is satisfactory as they both involve moving data elements, which is expensive Idea: Instead of moving data elements to a fixed position for front, let front advance through the array. Hmmm….what do we do when front catches up with rear? 36
  • 37. Array-based Queue • Let’s assume that as elements are inserted into a queue, we store them in an array such that the first element is at index 0, the second element at index 1, and so on. • Using an array to store elements of a queue, such that the first element inserted, “A”, is at cell 0, the second element inserted, “B”, at cell 1, and so on. 37
  • 38. How to Implement a dequeue operation • The element to be removed is stored at index 0 of the array. • One strategy is to execute a loop to shift all other elements of the queue one cell to the left, so that the front of the queue is again aligned with cell 0 of the array. • Unfortunately, the use of such a loop would result in an O(n) running time for the dequeue method. • Allowing the front of the queue to drift away from index 0. In this representation, index f denotes the location of the front of the queue.38
  • 39. How to Avoid Loop • We will replace a dequeued element in the array with a null reference, and maintain an explicit variable f to represent the index of the element that is currently at the front of the queue. • Such an algorithm for dequeue would run in O(1) time. • After several dequeue operations, this approach might lead to the configuration portrayed in Figure. • However, there remains a challenge with the revised approach. With an array of capacity N, we should be able to store up to N elements before reaching any exceptional case. 39
  • 40. Using an Array Circularly • In developing a robust queue implementation, we allow both the front and back of the queue to drift rightward, with the contents of the queue “wrapping around” the end of an array, as necessary. • Assuming that the array has fixed length N, new elements are enqueued toward the “end” of the current queue, progressing from the front to index N −1 and continuing at index 0, then 1. • Figure illustrates such a queue with first element F and last element R. 40
  • 41. Circular Queue • Use an array of size N in a circular fashion • Two variables keep track of the front and size f index of the front element sz number of stored elements • When the queue has fewer than N elements, array location r = (f + sz) mod N is the first empty slot past the rear of the queue Q 0 1 2 rf normal configuration Q 0 1 2 fr wrapped-around configuration 41
  • 43. Queue Operations • We use the modulo operator (remainder of division) Algorithm size() return sz Algorithm isEmpty() return (sz == 0) Q 0 1 2 rf Q 0 1 2 fr 43
  • 44. Queue Operations (cont.) Algorithm enqueue(o) if size() = N  1 then throw IllegalStateException else r  (f + sz) mod N Q[r]  o sz  (sz + 1) • Operation enqueue throws an exception if the array is full • This exception is implementation- dependent Q 0 1 2 rf Q 0 1 2 fr 44
  • 45. Queue Operations (cont.) • Note that operation dequeue returns null if the queue is empty Algorithm dequeue() if isEmpty() then return null else o  Q[f] f  (f + 1) mod N sz  (sz  1) return o Q 0 1 2 rf Q 0 1 2 fr 45
  • 46. Queue Interface in Java • Java interface corresponding to our Queue ADT • Assumes that first() and dequeue() return null if queue is empty public interface Queue<E> { int size(); boolean isEmpty(); E first(); void enqueue(E e); E dequeue(); } 46
  • 49. Comparison to java.util.Queue • Our Queue methods and corresponding methods of java.util.Queue: 49
  • 50. Application: Round Robin Schedulers • We can implement a round robin scheduler using a queue Q by repeatedly performing the following steps: 1. e = Q.dequeue() 2. Service element e 3. Q.enqueue(e) Shared Service Queue EnqueueDequeue 50
  • 51. Resources/ References • Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein 3rd, 2009, MIT Press and McGraw-Hill. • Data Structures: Abstraction and Design Using Java, Elliott B. Koffmann, 2nd, 2010, Wiley. • Data Structures and algorithm analysis in java, Mark A. Weiss, 3rd, 2011, Prentice Hall. • Frank M. Carrano, Data Structures and Abstractions with Java™, 3rd Edition, Prentice Hall, PEARSON, ISBN-10: 0-13-610091-0. • This lecture used some images and videos from the Google search repository to raise the understanding level of students. https://www.google.ie/search? Dr. Muhammad M Iqbal* 51